UPDATED ANSWER
If the ObjectValue contains multiple arrays, the following code demonstrates how to extract all addresses and combine them into a single array. Comments are provided within the code for better understanding.
const name = { john: [ { age: 21, address: 'LA', }, { age: 23, address: 'Franch', } ], sam: [ { age: 26, address: 'California' }, { age: 24, address: 'Swiss' } ] }
var ObjectValues = Object.values(name);
// Apply map method to ObjectValue to extract all addresses
var result = ObjectValues.map((ObjectValue) => {
return ObjectValue.map(item => item.address);
});
// Combine all child arrays into a single array
result = [].concat.apply([], result);
console.log(result);
Using forEach loop to extract all addresses into a single array
const name = { john: [ { age: 21, address: 'LA', }, { age: 23, address: 'Franch', } ], sam: [ { age: 26, address: 'California' }, { age: 24, address: 'Swiss' } ] }
var ObjectValues = Object.values(name);
var result = [];
ObjectValues.forEach((ObjectValue) => {
ObjectValue.map(item => result.push(item.address));
});
console.log(result);
Creating a function for best practice
const name = { john: [ { age: 21, address: 'LA', }, { age: 23, address: 'Franch', } ], sam: [ { age: 26, address: 'California' }, { age: 24, address: 'Swiss' } ] }
console.log(getAddress(name));
function getAddress(data) {
let result = []; // initialize storage
Object.values(data).forEach(ObjectValue => {
ObjectValue.map(item => result.push(item.address));
});
return result; // return extracted addresses
}
OLD ANSWER
Object.entries
returns arrays of Objects in [key, value] pairs. To extract only the "value" list of an object, use Object.values
instead.
After extracting all value lists using Object.values
, you can then use either map
or forEach
method to retrieve all addresses.
const name = {
john: [
{
age: 21,
address: 'LA',
}
],
sam: [
{
age: 26,
address: 'California'
}
]
}
var ObjectValues = Object.values(name);
// Using map method to extract addresses
var result = ObjectValues.map(ObjectValue => ObjectValue[0].address);
console.log(result) // Check the extracted addresses
// Using forEach method
var result = []
ObjectValues.forEach(ObjectValue => result.push(ObjectValue[0].address));
console.log('With forEach method')
console.log(result)