0

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

3 Answers 3

2

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)
Sign up to request clarification or add additional context in comments.

Comments

2
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

Comments

0
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(".")))
}

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.