javascript - 从嵌套对象中检索数据
问题描述
我只有这个对象示例:
{
id: 301
payload: {
1: {
house_no: 1234,
city: London
},
2: {
house_no: 0000
city: Paris
}
}
}
我只需要提取house_no and city
1 和 2 的值。我尝试过像这样遍历:*传递给循环的地址是上面的对象
let item = [];
for(let x in address){
item.push(item[x]);
}
console.log('Address', item.city);
这给了我带有未定义元素的数组:
[
0: undefined
1: undefined
]
你们能否帮我检索每个 1,2 所需的数据:house_no and city
解决方案
Object.values(address.payload).map(({ house_no, city }) => ({ house_no, city }));
这会遍历 in 中的每个值address.payload
并返回带有house_no
和的对象数组city
。
const address = {
id: 301,
payload: {
1: {
house_no: 1234,
city: 'London'
},
2: {
house_no: 0000,
city: 'Paris'
}
}
};
const result = Object.values(address.payload).map(({ house_no, city }) => ({ house_no, city }));
console.log(result);
推荐阅读
- elasticsearch - 嵌套数组上的弹性搜索过滤器
- python - Python requests.post() 方法命令返回 200 status_code 属性而不是 500
- angular - 如何在 Ionic/Angular 上使用不同的“模板”
- spring-boot - 什么是微服务,是否与 MVC 有联系
- r - 包括 scale.=F 作为插入符号序列中 preProcess 的参数?
- python - 在python中概括时间戳格式
- php - 如何有条件地验证 Laravel 7 中的数组输入?
- android - axios 请求在 Android(Cordova 容器)上引发“网络错误”
- java - 每次我使用 Firebase 在 android studio 中打开应用程序时,如何停止询问 OTP?
- xml - 使用正则表达式验证 xsd 字符串