0

Let say I have two array of objects.

var arr1= [
  {
    pid: [ '1967', '967' ],
  },
  {
    pid: [ '910', '1967', '967' ],
  },
  {
    pid: [ '967' ],
  }
]

var arr2 = [ 
{ _id: '967', name: 'test pid' }, 
{ _id: '1967', name: 'test one test' },
{ _id: '910', name: 'this is test name' }  
]

is there any way I can find the _id and name from array2 using the id from arr1 and replace element of arr1.pid. like below

arr1 = [
      {
        pid: [ { _id: '1967', name: 'test one test' }, { _id: '967', name: 'test pid' }],
      },
      {
        pid: [ { _id: '910', name: 'this is test name' }, { _id: '1967', name: 'test one test' }, { _id: '967', name: 'test pid' } ],
      },
      {
        pid: [ { _id: '967', name: 'test pid' } ],
      }
    ]

so far I have done as below

for (var i = 0; i < arr1.length; i++){
  var pids = arr1[i].pid
  for(var j = 0; j<pids.length; j++){
    var result = arr2.filter(obj => {
      return obj._id === pids[j]
    })
    console.log(result) //can not push this into arr1['pid']
  }
}
3
  • filter returns the matching element(s) in an array. You want a single item so use find. Commented Jun 6, 2020 at 7:08
  • Thank you @AluanHaddad. but how can i replace the object in arr1[pid] in same index. Commented Jun 6, 2020 at 7:11
  • 1
    arr1 = arr1.map(x => ({pid: x.pid.map(id => arr2.find(obj => obj._id === id) || obj)})) Commented Jun 6, 2020 at 7:16

2 Answers 2

4

You can map it and inside that you can find the elemenet from second array:

var arr1= [ { pid: [ '1967', '967' ], }, { pid: [ '910', '1967', '967' ], }, { pid: [ '967' ], }];
var arr2 = [ { _id: '967', name: 'test pid' }, { _id: '1967', name: 'test one test' },{ _id: '910', name: 'this is test name' } ];


var result = arr1.map(k=>{
  k.pid = k.pid.map(p=>arr2.find(n=>n._id==p));
  return k;
});

console.log(result);

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

Comments

0
  1. Build an object from arr2, so that easy access given key.
  2. Use map on arr1 and update the array.

var arr1 = [
  {
    pid: ["1967", "967"],
  },
  {
    pid: ["910", "1967", "967"],
  },
  {
    pid: ["967"],
  },
];

var arr2 = [
  { _id: "967", name: "test pid" },
  { _id: "1967", name: "test one test" },
  { _id: "910", name: "this is test name" },
];

// Build an object to from array
const all = arr2.reduce(
  (acc, curr) => ((acc[curr._id] = { ...curr }), acc),
  {}
);
const res = arr1.map(({ pid }) => ({
  pid: pid.map((key) => ({ ...all[key] })),
}));

console.log(res);

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.