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

3 Answers 3

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

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

Comments

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

Comments

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

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.