1

I'm trying to merge two objects which, both have same similar key, but different values. I want them to keep the different keys and but place them together in the matching key value

here my first obj,

const obj1 = [
      {
        "p_id": 1,
        "name": "Peter",
        "status" : "Active"
      },
      {
        "p_id": 2,
        "name": "Kane",
        "status" : "Active"
      },
      {
        "p_id": 3,
        "name": "William",
        "status" : "Inactive"
      }
]


}

my second obj,

const obj2 = [
  { p_id: 1, type: 'home', no: '+01 234 5678' },
  { p_id: 1, type: 'work', no: '+09 111 2223' },
  { p_id: 2, type: 'home', no: '+12 345 6789' },
]

Actually I did something like this,

 obj1.forEach((item) => {
            Object.assign(item, {
                phone: obj2.find(
                    (o) => o.p_id === item.p_id
                )
            });
        });
// console.log(obj1) would be

[
      {
        "p_id": 1,
        "name": "Peter",
        "status" : "Active",
        "phone" : {type: 'home', no: '+01 234 5678'}       
      },
      {
        "p_id": 2,
        "name": "Kane"
        "status" : "Active",
        "phone" : {type: 'home', no: '+12 345 6789'} 
      },
      {
        "p_id": 3,
        "name": "William"
        "status" : "Inactive"
        "phone" : undefined
      }

]

but this is not I want. I want to be final result I need is the compare between these arrays – the final result should be like this:

const result = [
      {
        "p_id": 1,
        "name": "Peter",
        "status" : "Active",
        "phone" : [
           {type: 'home', no: '+01 234 5678'},
           {type: 'work', no: '+09 111 2223'}        
        ]
      },
      {
        "p_id": 2,
        "name": "Kane"
        "status" : "Active",
        "phone" : [
           {type: 'home', no: '+12 345 6789'}      
        ]
      },
      {
        "p_id": 3,
        "name": "William"
        "status" : "Inactive"
        "phone" : []
      }

]

Really appreciate your kind help, Thank you!

2
  • 2
    This is not a code-writing service. Show us an actual attempt you made, and give a proper explanation of what exactly the problem was with it. How to Ask, minimal reproducible example Commented Jul 9, 2021 at 7:53
  • @CBroe sure I understand, actually I did tried some different different method.. but finally I'm able to reach out something like this updated question. (I updated the question). Thanks Commented Jul 9, 2021 at 8:04

3 Answers 3

5

You can do something like this:

const users = [
  {
    p_id: 1,
    name: "Peter",
    status: "Active",
  },
  {
    p_id: 2,
    name: "Kane",
    status: "Active",
  },
  {
    p_id: 3,
    name: "William",
    status: "Inactive",
  },
];

const phoneNumbers = [
  { p_id: 1, type: "home", no: "+01 234 5678" },
  { p_id: 1, type: "work", no: "+09 111 2223" },
  { p_id: 2, type: "home", no: "+12 345 6789" },
];

const mergeArrays = (arr1, arr2) => {
  return arr1.map((obj) => {
    const numbers = arr2.filter((nums) => nums["p_id"] === obj["p_id"]);
    if (!numbers.length) {
      obj.phone = numbers;
      return obj;
    }
    obj.phone = numbers.map((num) => ({ type: num.type, no: num.no }));
    return obj;
  });
};

const result = mergeArrays(users, phoneNumbers);
console.log(result);

Explanation:

Use the filter method to find all the objects with the same id in the phoneNumbers array. Then loop using the map method on the phone numbers matched and return a phone number object without the id.

Sign up to request clarification or add additional context in comments.

Comments

2

Instead of Array.find try Array.filter method. find will only return the first element while filter will return all the elements which meet the condition:

Object.assign(item, {
    phone: obj2.filter(
       (o) => o.p_id === item.p_id
    )
 });

2 Comments

Thank you, actually this small code snippet tally with my solutions, but one thing @Shuvo final result phone attribute has p_id property as well. Is there anything to remove this p_id form result.phone object array would be nice
You can chain the map method to pick the properties you need: phone: obj2.filter((o) => o.p_id === item.p_id ).map(item => ({type: item.type, no: item.no}))
-1

Here the best way to do so


// intersect can be simulated via
const intersection = new Set([...mySet1].filter(x => mySet2.has(x)))

// difference can be simulated via
const difference = new Set([...mySet1].filter(x => !mySet2.has(x)))


Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.