如何从带有嵌套对象的对象中获取价值?

时间:2020-05-20 23:21:49

标签: javascript arrays json

我有一个嵌套的JSON。如何将对象和嵌套对象的值一起提取?

这里是示例:

const person = [
   {
      id: 1,
      name: 'Bob',
      address: {
         country: 'United State',
         city: 'New York'
      }
    },
    {
      id: 2,
      name: 'Vegan',
      address: {
         country: 'Los Angeles',
         city: 'New York'
      }
    }
]

如何同时获得具有name属性的country的值?

1 个答案:

答案 0 :(得分:0)

您可以使用array.reduce之类的

const person = [{
    id: 1,
    name: 'Bob',
    address: {
      country: 'United State',
      city: 'New York'
    }
  },
  {
    id: 2,
    name: 'Vegan',
    address: {
      country: 'Los Angeles',
      city: 'New York'
    }
  }
]

const list = person.reduce((list, item) => {
  return list.concat({
    name: item.name,
    country: item.address.country
  })
}, [])

console.log(list);