获取/更新具有特定子值的json元素

时间:2017-07-15 08:54:14

标签: javascript json

说我有以下json数组

[ { title: 'Demo', key: 'IJwARZ9P', image: '#EF6176' },
  { title: 'Test', key: 'O-q-XmoX', image: '#35A8C0' },
  { title: 'Example', key: 'lBZiB0QF', image: '#99C953' },
  { title: 'Greet', key: 'p6RZf9tt', image: '#F56E45' }    ]

我知道要更新的元素的标题。对于这个例子,我希望添加一个'描述'具有title: 'Test'的元素的元素。我有标题{...}存储的整个项目,所以我可以从那里访问标题,但我想知道如何在这个特定项目中添加元素。

道歉,如果我使用了任何不正确的术语,对于json来说是个新手。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

您可以使用Array.find()方法获取所需的项目。然后设置该项目的描述,这将更新数组中的项目,因为它是一个参考。



var data = [{
    title: 'Demo',
    key: 'IJwARZ9P',
    image: '#EF6176'
  },
  {
    title: 'Test',
    key: 'O-q-XmoX',
    image: '#35A8C0'
  },
  {
    title: 'Example',
    key: 'lBZiB0QF',
    image: '#99C953'
  },
  {
    title: 'Greet',
    key: 'p6RZf9tt',
    image: '#F56E45'
  }
];

// find first match with title "Test";
var testItem = data.find(function(item) {
  return item.title === "Test";
});

// set description of matching item (also updates in array since this is a reference).
testItem.description = "test description";

console.log(data);




答案 1 :(得分:0)

尝试使用

var a = [{
    title: 'Demo',
    key: 'IJwARZ9P',
    image: '#EF6176'
  },
  {
    title: 'Test',
    key: 'O-q-XmoX',
    image: '#35A8C0'
  },
  {
    title: 'Example',
    key: 'lBZiB0QF',
    image: '#99C953'
  },
  {
    title: 'Greet',
    key: 'p6RZf9tt',
    image: '#F56E45'
  }
];

for (var b of a) {
  if (b.title == "Test") {
    b.description = "test description";
  }
}

console.log(a);