javascript - 在javascript中循环对象数组
问题描述
如何循环获取所有地址?
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]);
}
解决方案
更新的答案
如果 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
orforEach
方法来获取所有地址列表
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)
推荐阅读
- python - 比较字节串和 cv2.imread
- c# - 如何统一检查 Rigibody2D 上的重力比例?
- vagrant - 安装 linux-mint xfce 桌面时 vagrant 校验和错误
- swiftui - AppStorage 与 CoreData
- php - PHP ffmpeg 将 GIF 转换为 MP4
- android - 约束布局指南百分比屏幕尺寸不起作用
- javascript - 当变量改变时,while循环应该停止
- go - 为什么两个 goroutine 的控制台输出看起来是同步的
- node.js - 无法 POST 表单 NodeJS Express
- reactjs - FullCalendar React 标题自定义按钮未显示