Home > Enterprise >  Extracting values out of an array of objects?
Extracting values out of an array of objects?

Time:04-28

I am trying to extract id from the below array of objects and so far I am able to give it a go with the below code but it is showing undefined and cannot get id , would you please check the code and adjust to get id out?

const array = [{
    contact: {
      id: 1,
      email: '[email protected]',

    },
    date: '2/4/22'
  },
  {
    contact: {
      id: 2,
      email: '[email protected]',

    },
    date: '2/4/22'
  }
]

function extractValue(arr, prop) {

  let extractedValue = [];

  for (let i = 0; i < arr.length;   i) {
    // extract value from property
    extractedValue.push(arr[i][prop]);
  }
  return extractedValue;
}


const result = extractValue(array, 'contact.id');
console.log(result);

CodePudding user response:

A good way to do this is the Array Map method

This will get all the id's from your array

const result = array.map((val) => val.contact.id)

CodePudding user response:

const extractValue = (array, path) => {
  const [first, second] = path.split('.')
  if (second) return array.map(obj => obj[first][second])
  
  return array.map(obj => obj[first])
}

const res = extractValue(array, 'contact.id')
console.log(res)
// => [ 1, 2 ]

this will support single and double level nested results

CodePudding user response:

function find(val, arr) {  
  for (let x of arr)
    val = val[x];
  return val;  
}
function extractValue(arr, prop) {
 return array.map(x => find(x, prop.split(".")))
}
  • Related