Using Javascript or ES6, you can compare a nested array object with another array of elements and generate a new array based on

I am dealing with a complicated array structure as shown below

sectionInfo = [{id: 1, name:'ma'}, {id: 2, name:'na'}, {id: 3, name:'ra'}, {id: 4, name:'ka'}, {id: 5, name:'pa'}];

abc = [{id:'1', name:'zam', sections:['1',4]}, {id:'2', name:'dam', sections:['3']}, {id:'3', name:'nam', sections:['2','4']}];

My task is to iterate through the abc array based on sections and replace the elements with corresponding values from sectionDetail array.

I attempted to accomplish this by looping it into a new variable, but I encountered issues where my sections were being replaced every time. Below is the code snippet that I tried:

const matchingData = [];
const updatedSectionList = [];
abc.forEach((item, i) => {
    sectionDetail.forEach((val, index) => {
      item.section.forEach((value, x) => {
        if (value == val.Id) {
          matchingData.push(val);
        }
      });
    });
    updatedSectionList.push({
      Name: item.Name,
      Data: matchingData
    });
  });

Ultimately, I aim to generate a new array structured like this

xyz = [{name:'zam',  sections:[{id: 1, name:'ma'}, {id: 4, name:'ka'}]},
{name:'dam',  sections:[{id: 3, name:'ra'}]}, {name:'nam',  sections:[{id: 2, name:'na'}, {id: 4, name:'ka'}]}];

I hope this explanation makes sense and I look forward to any helpful responses.

Answer №1

To filter the sections from the sectionDetail based on whether the object.id inside it is included in the sections of abc, I assigned numeric values to both indexes since one was a string and the other an integer.

sectionDetail = [{id: 1, name:'ma'}, {id: 2, name:'na'}, {id: 3, name:'ra'}, {id: 4, name:'ka'}, {id: 5, name:'pa'}];

abc = [{id:'1', name:'zam', sections:['1',4]}, {id:'2', name:'dam', sections:['3']}, {id:'3', name:'nam', sections:['2','4']}];

xyz = abc.map(item => ({...item, sections: sectionDetail.filter(sect => item.sections.map(id => parseInt(id)).includes(parseInt(sect.id)))}));

console.log(xyz);

Answer №2

If you utilize a Map object, you can then map the data using the elements from the sectionDetail array.

var sectionDetail = [{ id: 1, name: 'ma' }, { id: 2, name: 'na' }, { id: 3, name: 'ra' }, { id: 4, name: 'ka' }, { id: 5, name: 'pa' }],
    data = [{ id: '1', name: 'zam', sections: ['1', 4] }, { id: '2', name: 'dam', sections: ['3'] }, { id: '3', name: 'nam', sections: ['2', '4'] }],
    map = new Map(sectionDetail.map(o => [o.id, o])),
    result = data.map(({ name, sections }) =>
        ({ name, sections: sections.map(id => map.get(+id)) })
    );

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №3

If you're looking to strip the id from abc objects and substitute the sections array elements with their respective details objects, you can achieve this using forEach and map methods. The following code snippet also includes some preprocessing of the sections array for better efficiency.

const sections = sectionDetail.reduce((result, section) => {
    result[section.id] = section;
    return result;
}, {});
abc.forEach(item => {
    delete item.id;
    item.sections = item.sections.map(id => sections[id]);
});

Answer №4

Give this a try:

const sectionDetail = [
    { id: 1, name: 'apple' },
    { id: 2, name: 'banana' },
    { id: 3, name: 'cherry' },
    { id: 4, name: 'date' },
    { id: 5, name: 'fig' }];

const abc = [
    { id: '1', name: 'zebra', sections: ['1', 4] },
    { id: '2', name: 'dog', sections: ['3'] },
    { id: '3', name: 'cat', sections: ['2', '4'] }
];

const desired = abc.map(({id, name, sections}) => {
    return {id, name, sections : sectionDetail.filter(f => {
        return sections.map(s => +s).includes(f.id)
    })};

})

console.log(desired);

In the code +s is converting to a Number type.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting a JavaScript Script Issue in a NextJs Class

I have been working on my website and decided to incorporate an FAQ page. I used a template for the FAQ section and tried to implement Javascript in my NextJs project, but unfortunately, it's not functioning as expected. var faq = document.getEle ...

Resizing svg to accommodate a circle shape

As I work on my vue.js app that involves a plethora of diverse icons, I made the decision to create a small icons builder in node.js. The purpose is to standardize their usage and also "crop" each SVG so it fits perfectly within its parent container by uti ...

The error message "TypeError: usert.addItem is not a function" indicates that

Currently in the process of developing a discord bot using discord.js, sequelize, and sqlite for database management. Encountering an issue with a custom function that is not being recognized as defined by the terminal, despite me confirming its definition ...

Stopping free jqgrid disabled toolbar buttons from reacting to mouse clicks can be achieved by implementing specific coding techniques that

When using Free jqgrid, toolbar disabled buttons may trigger click events on mouse clicks which can lead to invalid code execution. To demonstrate this, open the page below in Chrome and click on a disabled inline edit or pager button. A rectangle will app ...

Why isn't the hover function working on the table row element?

When I try to apply a hover effect on tbody and td elements, it works perfectly. However, when I apply the same effect to the tr element, it doesn't work as expected. I am using inline style (js pattern) rather than CSS code and incorporating Radium i ...

When using jQuery to focus on an input element, the cursor fails to show up

Looking to enhance user experience by focusing on an input element upon clicking a specific div. The HTML structure being used is as follows: <div class="placeholder_input"> <input type="text" id="username" maxlength="100" /> <div ...

Not sure about the Fat Arrow (=>) function

Hey there, I've been diving into NextJs and came across this issue: This Module is Functional const GlobalStyles = () => ( <> <Global styles={css` body { color: #000000; } `} ...

GATSBY: Error: Unable to find the specified property 'includes' within an undefined value

I'm struggling to figure out how to properly filter images in my portfolio website as discussed in this post… Every time I attempt it, I encounter the following error: "TypeError: Cannot read property 'includes' of undefined" D ...

The CSS files are not loading automatically in my React application using Vite

I am facing an issue with importing css and js files into a view in React using vite. The styles are not loading properly, and I have to keep commenting and uncommenting the imports in my code for them to be recognized when entering the view. Below is a s ...

Notification triggered from the controller

I am currently developing a user management application in which I have to add a user to the database. When a button is clicked on the client screen (index.cshtml), a JQuery dialog box will appear allowing users to fill in the necessary details (AddUser.c ...

Which method is better for presenting data: PHP or JavaScript?

Currently, I am diving into vue.js on laracasts.com where Jeffrey Way demonstrates 2 ways to showcase data on a webpage. One method involves displaying data using Laravel foreach loops, while the other utilizes vue.js. This has led me to ponder: is there ...

The Action-Reducer Mapping feature is encountering a type error when handling multiple types of actions

Earlier today, I posed a question about creating a mapping between redux action types and reducers to handle each type explicitly. After receiving helpful guidance on how to create the mapping, I encountered an error when attempting to use it in creating ...

How to display JSON data in an Android ListView

When parsing my URL, I receive the following JsonObject: {"status":0,"items":"1333333454510|-7611868|-7222457" Now I need to extract each number separately as a long. If I attempt to convert it to a string, I encounter an error: org.json.JSONException: V ...

Which of the two async functions will be executed first?

const [counter, setCounter] = useState(0) Consider the scenario where we have two asynchronous functions, func1 and func2, both of which are responsible for updating the counter state. It is specified that func1 is supposed to execute before func2. async ...

Guide on setting up multiple Axios instances in NestJS

I'm in the process of migrating an existing Express application to NestJS. Currently, I have a configuration file where I define multiple axios instances for each microservice: export const writeModelApi = axios.create({ baseURL: getWriteModelApiUrl ...

What is the best way to refrain from utilizing the && logical operator within the mapStateToProps function in Redux?

When I'm trying to access a nested state in a selector, I often find myself having to use the && logical operators. const mapStateToProps = store => ({ image: store.auth.user && store.auth.user.photoURL; }); If I don't use ...

Once the PHP page loads, it becomes challenging for me to dynamically change values in JavaScript

Within my code snippet below, I am aiming to modify the initial value using a slider. The slider appears to be functioning correctly; however, it is not updating the values of timeout as indicated beneath the line $('ul.<?php echo $this->session ...

Troubleshoot my code for clustering markers on a Google map

I'm currently working on a piece of code to generate a Google map that contains 3 hidden points within one marker. The idea is that when the main marker is clicked, these points will either merge into one or expand into 3 separate markers. However, I& ...

Is it within the realm of possibility for a route-handling function to accept more than two parameters?

Recently, I started learning about node js and delved into the world of jwt authentication. While going through some code snippets, I came across a request handler in express that caught my attention. app.post('/login',function(req,res){...}); ...

I'm stumped as to why I'm having trouble loading JSON data into a DataFrame

Is there a way to convert the JSON "Data" section into a Pandas table easily? Below is my attempted code: import json import urllib.request import pandas url = urllib.request.urlopen('https://www.cryptocompare.com/api/data/coinlist/') json_obj ...