Home > database >  What is the best way to access key/values of a object array when I don't know them?
What is the best way to access key/values of a object array when I don't know them?

Time:09-21

I have this array above and I need every property of it

let arr = [{'John': 0}, {'Doe': 50}, {'Marry': 100}]

How could I extract every single key/value of it, once in theory, I don't know any of them? I have already tried using object.keys but it returns the indexes of my array.

CodePudding user response:

This should work

const arr = [{'John': 0}, {'Doe': 50}, {'Marry': 100}];


// to iterate over each element in the arry  
arr.forEach(a => {
    // To Iterate over each key in the element object
    Object.keys(a).forEach(k => {
      // to print the value of the 'k' key
      console.log(k   ' : '   a[k]);
  })
})

CodePudding user response:

If you want to collect all the keys and values of a nested array of objects, you can use Array.prototype.reduce and then collect the keys and values of the nested objects in separate nested arrays, using Object.keys() and Object.values() respectively:

const arr = [{'John': 0}, {'Doe': 50}, {'Marry': 100}];

const allKeysAndValues = arr.reduce((acc, cur) => {
  acc.keys.push(...Object.keys(cur));
  acc.values.push(...Object.values(cur));
  return acc;
}, { keys: [], values: [] });

console.log(allKeysAndValues);

CodePudding user response:

1) You can use flatMap and Object.keys to get keys from an array of objects.

let arr = [{ John: 0 }, { Doe: 50 }, { Marry: 100 }];

const result = arr.flatMap((o) => Object.keys(o));
console.log(result);

2) To find all values in an array

let arr = [{ John: 0 }, { Doe: 50 }, { Marry: 100 }];

const values = arr.flatMap((o) => Object.values(o));
console.log(values);

3) If you want to find out all keys and values in an object

let arr = [{ John: 0 }, { Doe: 50 }, { Marry: 100 }];

const result = {
  keys: [],
  values: [],
};

for (let obj of arr) {
  Object.entries(obj).map(([k, v]) => {
    result.keys.push(k);
    result.values.push(v);
  });
}

console.log(result);

CodePudding user response:

A one liner could be

 let arr = [{'John': 0}, {'Doe': 50}, {'Marry': 100}]
 
 console.log( arr.map( obj => Object.entries(obj)));

  • Related