首页 > 解决方案 > 从嵌套对象中检索数据

问题描述

我只有这个对象示例:

{
id: 301
 payload: {
 1: {
  house_no: 1234,
  city: London
  },
 2: {
  house_no: 0000
  city: Paris
  }
 }
}

我只需要提取house_no and city1 和 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

标签: javascript

解决方案


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);


推荐阅读