Ansari Hi
Ansari Hi

Reputation: 1

Please help to Convert Array to Object

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" }
];

Upvotes: 0

Views: 71

Answers (3)

theunknownSAI
theunknownSAI

Reputation: 330

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);

Upvotes: 0

Fabrizio Beccaceci
Fabrizio Beccaceci

Reputation: 430

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

Upvotes: 1

Turbo
Turbo

Reputation: 688

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"}]

Upvotes: 0

Related Questions