Skip to content
Advertisement

Copy obj filtering selected elements in javascript

I’m trying to create a new obj similar to my input, but containing only the elements from a selected id list.

const arrObj = [
{
  value = 1,
  name = 'a'
},
{
  value = 2,
  name = 'e'
},
{
  value = 3,
  name = 'i'
},
{
  value = 4,
  name = 'o'
},
{
  value = 5,
  name = 'u'
},
];

const selectedIds = [1,4,5];

// How can I make this selectedObjs as the same type as arrObj, but only containing the selected elements?
const selectedObjs = [];

Advertisement

Answer

Use Array.filter

const arrObj = [
  {
    value: 1,
    name: "a",
  },
  {
    value: 2,
    name: "e",
  },
  {
    value: 3,
    name: "i",
  },
  {
    value: 4,
    name: "o",
  },
  {
    value: 5,
    name: "u",
  },
];
const selectedIds = [1, 4, 5];
const selectedObjs = arrObj.filter(node => selectedIds.includes(node.value));
console.log(selectedObjs)
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement