0

I need to convert an array with only ids and an object with Id & Name need to find object array element from the object and create new Object

App.js:

["111","114","117']

Object:

[
  { id: "111", Name: "Jerry" },
  { id: "112", Name: "Tom" },
  { id: "113", Name: "Mouse" },
  { id: "114", Name: "Minny" },
  { id: "115", Name: "Mayavi" },
  { id: "116", Name: "Kuttoosan" },
  { id: "117", Name: "Raju" }
];

Result Need:

[
  { id: "111", Name: "Jerry" },
  { id: "114", Name: "Minny" },
  { id: "117", Name: "Raju" }
];
Ryan Le
  • 7,708
  • 1
  • 13
  • 23
Ansari Hi
  • 1
  • 1
  • Does this answer your question? [Filter array of objects with another array of objects](https://stackoverflow.com/questions/31005396/filter-array-of-objects-with-another-array-of-objects) – A.T. Aug 28 '21 at 10:09

3 Answers3

1
const array = ["111", "114", "117"];

const object = [
  { id: "111", Name: "Jerry" },
  { id: "112", Name: "Tom" },
  { id: "113", Name: "Mouse" },
  { id: "114", Name: "Minny" },
  { id: "115", Name: "Mayavi" },
  { id: "116", Name: "Kuttoosan" },
  { id: "117", Name: "Raju" }
];

const result = object.filter(o => array.includes(o.id));

This should give you the result you want, pay attention that what you called object actually is an array of objects, as far as i understood you want keep only the object with an id contained in the first array, so as i shown just filter them

Ryan Le
  • 7,708
  • 1
  • 13
  • 23
0

I think you can just use .filter() to achieve the same result.

const targetIds = ["111","114","117"];
const nameObjects = [{id:"111", Name:"Jerry"}, {id:"112", Name:"Tom"}, {id:"113", Name:"Mouse"}, {id:"114", Name:"Minny"}, {id:"115", Name:"Mayavi"}, {id:"116", Name:"Kuttoosan"}, {id:"117", Name:"Raju"}];
const filtered = nameObjects.filter((obj) => targetIds.indexOf(obj.id) !== -1);

// Which should give the result you need
// [{id:"111", Name:"Jerry"}, {id:"114", Name:"Minny"},{id:"117", Name:"Raju"}]
Turbo
  • 548
  • 5
  • 13
0

Use the .filter() to get the result

const ids = ["111", "114", "117"];
const nameids = [
  { id: "111", Name: "Jerry" },
  { id: "112", Name: "Tom" },
  { id: "113", Name: "Mouse" },
  { id: "114", Name: "Minny" },
  { id: "115", Name: "Mayavi" },
  { id: "116", Name: "Kuttoosan" },
  { id: "117", Name: "Raju" }
];
const result = nameids.filter(res => ids.includes(res.id));
console.log(result);
Ryan Le
  • 7,708
  • 1
  • 13
  • 23
theunknownSAI
  • 300
  • 1
  • 4