首页 > 解决方案 > 如何更改对象键值?

问题描述

如何仅更改对象键中的值?

例如:我想将 keyvalue 更新list_one为任何值。

var ar = [
  {
    "list_one": [
      { id:1,product: 'Fortenza'}
    ]
  },
  {
    "list_two": [
      { id:4,product:'SETLIQUI'}
    ]
  }
]

我的代码:

var setTitleProduct = function(key="list_one",index=0) {
  Object.keys(ar[index][key])[0] = 'new value'; //I know this doesnt work
  console.log(ar[index][key]);
}
setTitleProduct("list_one",0)

像这样。 http://i.imgur.com/v6rTSfF.png

标签: javascript

解决方案


var ar = [
  {
    "list_one": [
      { id:1,product: 'Fortenza'}
    ]
  },
  {
    "list_two": [
      { id:4,product:'SETLIQUI'}
    ]
  }
]

ar[0]['someValue'] = ar[0]['list_one'];
delete ar[0]['list_one'];

console.log(ar);


推荐阅读