Construct a new array by combining elements from two existing arrays

There are two arrays, details and options, each originating from different sources such as web API requests.

details: [
      { id: 'groups', option: true },
      { id: 'category', option: false }
]


 options: {
        groups: [ 
          { id: 'g1' },
          { id: 'g2' }
        ],
        category: [
          { id: 'c1' },
          { id: 'c2' }
        ],
        other: [
          { id: 'o1' },
          { id: 'o2' }
        ],
    }

The goal is to merge these arrays in the following format:

combined: [
        groups: 
            {
                options:[ 
                    { id: 'g1' },
                    { id: 'g2' }
                ], 
                details: { option: true}
            },
        category: 
                {
                 options:   [ 
                    { id: 'c1' },
                    { id: 'c2' }
                ], 
                details: { option: false}
            },
    ]

If any id from details matches an id in the options property, it should be placed in a new array under the same property name. All details except for the id should go into the related details property.

What would be the most effective method of achieving this task? Can lodash library handle such merging operation?

Answer №1

If you're interested in only the elements that are present in both options and details (intersection):

var details = [
      { id: 'groups', option: true },
      { id: 'category', option: false }
]

var options = {
        groups: [ 
          { id: 'g1' },
          { id: 'g2' }
        ],
        category: [
          { id: 'c1' },
          { id: 'c2' }
        ],
        other: [
          { id: 'o1' },
          { id: 'o2' }
        ]
    }

var combined = {};
details.forEach(({id: id, option: option}) => {
  if (options[id]) {
    combined[id] = combined[id] || {};
    combined[id].options = options[id];
    combined[id].details = {option: option};
  }
})

console.log(JSON.stringify(combined, null, "\t"))
/*
{
  "groups": {
    "options": [
      {
        "id": "g1"
      },
      {
        "id": "g2"
      }
    ],
    "details": {
      "option": true
    }
  },
  "category": {
    "options": [
      {
        "id": "c1"
      },
      {
        "id": "c2"
      }
    ],
    "details": {
      "option": false
    }
  }
}
*/

If your goal is to keep all elements from options and details regardless of matching or not (union):

var details = [
      { id: 'groups', option: true },
      { id: 'category', option: false }
]

var options = {
        groups: [ 
          { id: 'g1' },
          { id: 'g2' }
        ],
        category: [
          { id: 'c1' },
          { id: 'c2' }
        ],
        other: [
          { id: 'o1' },
          { id: 'o2' }
        ]
    }

var combined = {};

Object.keys(options).forEach(id => {
  combined[id] = {};
  combined[id].options = options[id];
})
details.forEach(({id: id, option: option}) => {
  combined[id] = combined[id] || {};
  combined[id].details = {option: option};
})

console.log(JSON.stringify(combined, null, "\t"))
/*
{
  "groups": {
    "options": [
      {
        "id": "g1"
      },
      {
        "id": "g2"
      }
    ],
    "details": {
      "option": true
    }
  },
  "category": {
    "options": [
      {
        "id": "c1"
      },
      {
        "id": "c2"
      }
    ],
    "details": {
      "option": false
    }
  },
  "other": {
    "options": [
      {
        "id": "o1"
      },
      {
        "id": "o2"
      }
    ]
  }
}
*/

Answer №2

To store specific data, make use of the [] syntax when assigning values.

properties['set']['specifics'] = true
properties['set']['classification'] = false

Answer №3

Here is the resolution to address your issue:

var details= [
      { id: 'groups', option: true },
      { id: 'category', option: false }
];


var options= {
        groups: [ 
          { id: 'g1' },
          { id: 'g2' }
        ],
        category: [
          { id: 'c1' },
          { id: 'c2' }
        ],
        other: [
          { id: 'o1' },
          { id: 'o2' }
        ],
    };
 
var combined = {};

for (var i= 0;i<details.length;i++){
var obj = {}
obj.options=options[details[i].id];
obj.details = {};
obj.details.option=details[i].option;
combined[details[i].id] = obj;

}

console.log(combined)

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

The controller is referencing $rootScope which has not been properly defined

Here is my understanding of the controller concept. Whenever I launch the application, an error message appears saying "$rootScope is not defined." Can someone provide assistance in identifying the issue? var webadmin = angular.module('PcPortal' ...

Customize the style of the title bar in a jQuery dialog

Is there a way to change the title bar color of specific jQuery dialogs without affecting all of them? I tried using the property dialogClass:"myClass" in certain dialogs, but it only changes the body of the dialog. Any suggestions would be greatly apprec ...

Chrome not responding to ajax requests

Having an issue with a script that uses ajax to post text: <?php if (isset($_POST['q'])) { echo 'q is '.$_POST['q']; } else { ?> <!DOCTYPE HTML> <html> <head> <script ...

Can an EJS variable be transferred to an Angular ng-repeat filter?

I am currently working on a profile page where I need to display a user's name in plain text using <%= user.local.name %>. This requires querying the database through Mongoose. My issue now is figuring out how to pass that value to an Angular ng ...

javascript with python

Currently, I'm in the process of parsing a html page. I've experimented with spynner, selenium, and mechanize, however none of them have been effective when dealing with JavaScript in this particular scenario. Is there anyone who can provide som ...

guide on adding a variable to the link_to path

In my attempt to incorporate a variable into the link_to function below: <%= link_to '<button type = "button">Players</button>' .html_safe, live_players_path(:Team => @tmf) %> Whenever I click on this link, it seems to ...

json outputting text instead of a data structure

I am working with some PHP code that involves converting an array to a JSON string and then retrieving it in JavaScript. Here's what the code looks like: $age = implode(',', $wage); // The object returns: [1,4],[7,11],[15,11] $ww = json_e ...

Implementing manual updates for the bootstrap color picker

I have integrated a color picker from Bootstrap into my project. You can find the color picker here: To change the background color of an element on my page, I am using the following code: <input type="text" id="mypicker" name="mypicker" value="" cla ...

Adjusting the dimensions of :before with JavaScript: A Step-by-Step Guide

There's this CSS3 tag named body:before that I'm working with, and I'm looking to adjust the height and width of body:before using JavaScript. Any suggestions on how to achieve this? ...

Flask is failing to display AJAX data

Looking to embark on a Flask project involving sending an AJAX request. In the Flask code, I want to assign a variable to handle the request and display it on the page using a Jinja variable. Flask from flask import Flask,render_template,request app = Fla ...

PHP: How to Return a Multidimensional Array and Separate Variables Simultaneously

I am trying to send a 2D array with multiple individual variables from a PHP script to a JavaScript client using AJAX. Despite many attempts, I haven't been able to figure out how to include additional individual variables (like $var1, $var2, $var3) i ...

Array of JSON data passed in the request body

Recently, I have been attempting to pass JSON data to my req.body. The data structure is as follows: answers = ["A","B"]; //An array to be included in the JSON Object var Student_Answers = { //JSON object definition Answers: answers, matricNumber: ...

Encountering a 'MODULE_NOT_FOUND' error when using the Svelte `node scripts/setupTypeScript.js` command

I encountered a problem in my Svelte project: Although my files display no errors in VSCode, when I run npm run dev --, all Typescript syntax is flagged as erroneous, and the server fails to start. To address this issue, I attempted removing all node_mod ...

What is the best way to implement data validation for various input fields using JavaScript with a single function?

Users can input 5 numbers into a form, each with the same ID but a different name. I want to validate each input and change the background color based on the number entered - red for 0-5, green for 6-10. I wrote code to change the color for one input box, ...

Issue encountered during execution of a mongodb function within a while loop in nodejs

To ensure that a generated id doesn't already exist in the database, I have implemented the following code: let ssid; while ( ssid == undefined ) { let tempSId = assets.makeid(30); MongoClient.connect(mongoUrl, function(err, db) { if ( ...

When can the FullName property of the Type object in C# be null?

The MSDN article on Type.FullName explains that this property returns null if the current instance represents a generic type parameter, an array type, pointer type, or byreftype based on a type parameter, or a generic type that is not a generic type def ...

Why are all the values in my list appearing as undefined after parsing with JSON?

Just starting out with this project. I'm attempting to print a list, where the names come from a button. However, all the names are showing up as undefined. I suspect it has something to do with local storage, but I can't pinpoint the issue. < ...

transferring data from JavaScript to PHP variables

Currently, I am working on a project that involves using ajax to access the database asynchronously. The value retrieved is stored in a JavaScript variable like this: var content=xmlhttp.responseText; My next step is to pass this value to the PHP module ...

How can I use the JQuery .load() method to send a POST request after a successful ajax post?

Following a successful Ajax post, I am looking to render the template associated with POST using JQuery's .load() method in the handler function. Every time a successful POST is made, the GET request keeps getting called, resulting in the rendering of ...

Not able to scroll to top in Angular 2 when changing routes

I need help figuring out how to automatically scroll to the top of my Angular 2 website when the route changes. I've attempted the code below, but unfortunately, it's not working as expected. When transitioning from one page to another, the page ...