【问题标题】:Flatten nested JSON object展平嵌套的 JSON 对象
【发布时间】:2021-10-19 18:29:19
【问题描述】:

我有一个这样的 json 对象:

const people = {
name: 'My Name',
cities: [{city: 'London', country: 'UK'},{city: 'Mumbai', country: 'IN'},{city: 'New York', country: 'US'}],
}

我想要这样的输出:即对于每个城市,我想要展平数组。

[
  ['My Name', 'London', 'UK'], 
  ['My Name','Mumbai', 'IN'],
  ['My Name','New York', 'US']
]

我尝试过 flatten 等,但不知道如何实现这一点。 有人可以帮我吗? 谢谢, 萨西

【问题讨论】:

    标签: javascript json nested flatten


    【解决方案1】:

    如果你想要 JSON 输出:

    const people = {
      name: 'My Name',
      cities: [{city: 'London', country: 'UK'},{city: 'Mumbai', country: 'IN'},{city: 'New York', country: 'US'}],
    }
    
    let result = people.cities.map(data => {
      return {
        name: people.name,
        city: data.city,
        country: data.country
      }
    })
    
    console.log(result)

    为多人扩展:

    const peopleExtended = [{
      name: 'My Name',
      cities: [{
        city: 'London',
        country: 'UK'
      }, {
        city: 'Mumbai',
        country: 'IN'
      }, {
        city: 'New York',
        country: 'US'
      }],
    }, {
      name: 'Person 2',
      cities: [{
        city: 'Birmingham',
        country: 'UK'
      }, {
        city: 'Delhi',
        country: 'IN'
      }, {
        city: 'New York',
        country: 'US'
      }],
    }]
    
    function flattenCities(person) {
      return person.cities.map(data => {
        return {
          name: person.name,
          city: data.city,
          country: data.country
        }
      })
    }
    
    peopleExtended.forEach(person => {
        let flatArray = flattenCities(person);
      console.log(person.name, flatArray)
    })

    【讨论】:

    • 这与 JSON 完美搭配。为了扩展它,如果我有一个 json 数组,例如: const people =[ { name: 'My Name', urban: [{city: 'London', country: 'UK'},{city: 'Mumbai', country: 'IN'},{city: 'New York', country: 'US'}], },{ name: 'Person 2', 城市: [{city: 'Birmingham', country: 'UK'}, {city: 'Delhi', country: 'IN'},{city: 'New York', country: 'US'}], }] 这是如何工作的?谢谢
    • 当然!只需将扁平化代码放入一个函数中,然后在每次遍历一个人时调用它。查看我的编辑。
    【解决方案2】:

    这应该可以解决问题!

    const people = {
      name: 'My Name',
      cities: [{city: 'London', country: 'UK'},{city: 'Mumbai', country: 'IN'},{city: 'New York', country: 'US'}],
    }
    
    function flattenIt(obj) {
      const name = obj.name;
      const cityData = obj.cities;
      return cityData.map(({city, country}) => [name, city, country])
    }
    
    console.log(flattenIt(people));

    【讨论】:

    • 你是明星!优秀的答案。我挣扎了几个小时,你让我的一天变得很轻松。
    猜你喜欢
    • 2012-05-29
    • 2020-03-02
    • 1970-01-01
    • 2019-01-17
    • 2019-01-26
    • 2020-01-21
    • 1970-01-01
    • 2018-10-24
    相关资源
    最近更新 更多