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

Stop users from being able to copy text on their smartphones' internet browsers

I am currently working on creating a competitive typing speed challenge using JavaScript. Participants are required to type all the words they see from a div into a textarea. In order to prevent cheating, such as copying the words directly from the div, o ...

Guide on how to use JavaScript to swipe through loaded epub files in both lateral directions

Hello everyone, I have a question about implementing swipe functionality on a loaded epub using JavaScript. I successfully loaded the epub into a div and now I need to enable swipe left and right gestures on that div. I found a jQuery script that should a ...

Identifying the presence of a mouse inside an element using jQuery

I am working on a website that utilizes jQuery. The structure of my page is as follows: <div id="page"> <!-- Content goes here --> <div id="content"> <div class="row"> <div class="col"><!-- content goes here ...

Interfacing my Node.js REST API with AngularJS

I've got angular code that works with a local JSON file: App.controller('bodyController', ['$scope','$http',function($scope,$http){ $http.get('data.json').success(function(data){ $scope.data=data; }).error ...

Are jQuery plugins offering accessible public functions?

I am currently working on enhancing the functionality of a jQuery plugin. This plugin serves as a tag system and utilizes autocomplete provided by jQuery UI. Presently, there is no direct method (aside from parsing the generated list items) to determine ...

Is NextJS rendering solely on the server, or is it capable of rendering on both

Within my users.js JSX file, I have an exported component that looks like this: ... return <MainContainer keywords="users"> export default Users During the process of SSR/SSG, the browser displays the users HTML (comprising of <li> t ...

Having trouble with error code JSON Parse error: Struggling to understand JSON formatting

I am encountering a frustrating issue with a JSON parse error. I can't seem to determine whether the web service is faulty or if there's an issue with my fetch code. When testing the web service on Postman, it returns two objects. However, whenev ...

What is the best way to categorize variables?

How can I organize variables together: export let findbyc$: Observable<Object>; export let findbyi$: Observable<Object>; export let findbyo$: Observable<Object>; export let findbyob$: Observable<Object>; I would like to group them ...

Generating an in-page anchor using CKeditor 5

We are currently integrating CKEditor 5 into one of our projects. Our goal is to enable the end-user to generate an in-page anchor tag that can be accessed through other links (e.g., <a name='internalheading'> which can be navigated to via ...

Utilize Jquery's "find" function to showcase an image

I am attempting to showcase an image using jQuery. I have a function that accepts ID and PATH as parameters. The ID indicates the section (each section is an HTML page that loads upon user action). Additionally, there is a text area where I am displaying t ...

What is the reason for the filter not displaying the IFRAME?

I have a filter set up to automatically embed YouTube videos for user-generated content by searching for links and verifying if they are valid YouTube videos. If they are, the video should be embedded using standard iframe code; otherwise, it remains just ...

Updating state with new data in React: A step-by-step guide

Recently, I delved into the world of reactjs and embarked on a journey to fetch data from an API: constructor(){ super(); this.state = {data: false} this.nextProps ={}; axios.get('https://jsonplaceholder.typicode.com/posts') ...

Could Express be considered the most reliable and efficient application framework for NodeJS?

While I have some experience with Express, I haven't explored many other Node-based web application frameworks. It's clear that Express is lightweight and versatile, but my usage has been limited to small experimental projects rather than large-s ...

Adding new data to a Chart.js line graph in vue on form submission - A step-by-step guide

I'm struggling with dynamically updating my line chart with new data. I want the chart to refresh every time a user submits a form with new data. Currently, I can add new data to the datasets array in the data function of App.vue, but the chart doesn& ...

Utilizing a dynamic form action connected to an Express route

I've been grappling with creating an HTML form in my nodejs application that directs to the appropriate express route upon submission. After researching online, I stumbled upon a potential solution as outlined below: <script> $('#controlPa ...

Achieving Efficiency with Handlebars: Streamlining Remote Template Organization and

I am looking for a way to better organize my HB template by splitting it into different HTML files. In this case, I have created a file called helpers.html. This file contains two script tags: <script id='alert' type='text/template>... ...

Learn how to implement a call to 'next()' in Express and Node.js only after successfully creating schemas

I am currently developing an event app, and within my 'Event' schema, I have an array of 'Tag' schemas, allowing each event to be associated with one or more tags. Event: var EventSchema = new Schema({ ... tags: [{ type: Schema.Type ...

Tell me the permissions that a user possesses in discord.js

I need help creating a command using Discord.js that can display a user's permissions. For instance, the command could be $permissions @user and it should output something like: "User permissions within this guild: " I'm unsure if ...

Tips for rendering objects in webgl without blending when transparency is enabled

My goal is to display two objects using two separate gl.drawArrays calls. I want any transparent parts of the objects to not be visible. Additionally, I want one object to appear on top of the other so that the first drawn object is hidden where it overlap ...

Is it achievable to animate the offset with React Native Animated?

I am attempting to develop a dynamic drag and drop functionality, inspired by this example: My goal is to modify it so that when the user initiates the touch, the object moves upwards to prevent it from being obscured by their finger. I envision this move ...