skip to Main Content

I’m trying to add/combine 2 objects together without losing any duplicate information, simply adding the one to the other with inserting title for each object before adding them together. I’ve seen lot of ways of doing it none worked for my object below, tried the concat method and spread operator and they didn’t work.

const obj1 = [{"title": "1"}, {"title": "2"}]
const obj2 = [{"title": "2"}, {"title": "3"}]

Expected result:

const combined = {"obj1":[{"title": "1"}, {"title": "2"}], "obj2":[{"title": "2"}, {"title": "3"}]}

2

Answers


  1. Try something like:

    const combined = {“json1”: json1, “json2”: json2};
    

    It’s pretty similar to your expected output, but it directly calls the variables to put them in another constant.

    Login or Signup to reply.
  2. const combined = {
    
    "json1":obj1,
    
    "json2":obj2,
    };
    
    console.log(combined);
    

    This code creates a new object named combined with keys "json1" and "json2", each containing the respective obj arrays obj1 and obj2

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search