如何获取JSON密钥并添加额外的字段?

问题描述 投票:0回答:2

我正在尝试获取这些json对象的密钥,以便创建一个带有额外字段的新对象,以在React应用程序中创建表头。 JSON数据:

let example = [
  {
    id: 1,
    city: 'New York',
  },
 {
    id: 2,
    city: 'Paris',
  },
]

功能:

getKeys() {
    return example.map((key) => {
      return {
        cityName: key, // gets the whole array
        capital: false,
      };
    });
  }

我尝试Object.keys( example);,它返回整数; 0,1。在这种情况下如何获得密钥?谢谢。

javascript json reactjs
2个回答
0
投票

您正在尝试映射数组的键,因为example是一个数组。如果整个数组中的数据一致,则获取第一个元素example[0]并执行Object.keys()。所以Object.keys(example[0])


0
投票

如果您只想为数组中的项添加属性,则无需获取键。我认为对.map存在误解,它给出了数组中的单个项目/对象,而不是密钥。

也许这样的事情?

let example = [{
  id: 1,
  city: 'New York',
}, {
  id: 2,
  city: 'Paris',
}];

const modifiedArray = function(arr) {
  return arr.map(item => {
    return {
      id: item.id,
      cityName: item.city,
      capital: false,
    }; 
  })  
}

const newArray = modifiedArray (example);

console.log(newArray )
© www.soinside.com 2019 - 2024. All rights reserved.