如何回圈獲取所有地址?
const name = {
john: [
{
age: 21,
address: 'LA',
}
],
sam: [
{
age: 26,
address: 'California'
}
]
}
我有這樣的代碼,但仍然卡住了流程的進展
const array = Object.entries(name);
for (let i = 0; i < array.length; i ) {
console.log(array[i]);
}
uj5u.com熱心網友回復:
更新的答案
如果 ObjectValue 有多個陣列。請檢查下面的代碼,我還在代碼之間寫了一些注釋。
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);
// if single user have multiple data or address apply map method to ObjectValue too
var result = ObjectValues.map((ObjectValue) => {
return ObjectValue.map(item => item.address);
});
// try to print result before combining
// console.log(result);
// combine all child arrays into single array
result = [].concat.apply([], result);
console.log(result);
使用 forEach 回圈并獲取單個陣列中的所有地址
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);
只需撰寫一個函式以獲得最佳實踐
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 => {
// store address(data)
ObjectValue.map(item => result.push(item.address));
});
return result; // return data
}
舊答案
Object.entries 將回傳 [key, value] 對中的 Object 陣列
因此,不要使用 Object.entries 使用 Object.values(它將僅回傳物件的“值”串列)
現在使用 提取所有值串列后Object.values,現在只需使用map或forEach方法來獲取所有地址串列
const name = {
john: [
{
age: 21,
address: 'LA',
}
],
sam: [
{
age: 26,
address: 'California'
}
]
}
var ObjectValues = Object.values(name);
// map method
var result = ObjectValues.map(ObjectValue => ObjectValue[0].address);
// here I have used 0 index of an ObjectValue because ObjectValue is an array of single Object of data {age, address}
console.log(result) // check result
// forEach method
var result = []
ObjectValues.forEach(ObjectValue => result.push(ObjectValue[0].address));
console.log('With forEach method (?′?`?)')
console.log(result)
uj5u.com熱心網友回復:
在您的情況下,name它更像是一個哈希映射,因為鍵是字串(例如john和sam),而不是數字(0、1、2 等)。Object.entries()回傳鍵值對(參見MDN),這就是為什么array[i]它不起作用。
像下面這樣稍微改變回圈應該可以解決問題:
const array = Object.entries(name);
for (const [key, value] of Object.entries(array)) {
console.log(`${key}: ${value}`);
// logs john: [object Object] and sam: [object Object]
}
uj5u.com熱心網友回復:
這應該可以解決問題,
Object.values(name).map(([{address}])=>address) // ["LA", "California"]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/315799.html
標籤:javascript 数组 循环 目的
