简体   繁体   English

如何使用JSON.parse的reviver函数向数组中的每个对象添加数据?

[英]How do I use `JSON.parse`'s reviver function to add data to each object in an array?

Let's say I have the following JSON object saved in a variable like this: 假设我将以下JSON对象保存在这样的变量中:

var musicList = {
  "files": [
        {
          "title": "Ironic"
        },
        {
          "title": "It's Beginning To Look A Lot Like Christmas"
        },
        {
          "title": "Sweet Dreams"
        }
      ] 
};

This is for a learning exercise which has us turn this JSON object to a string and then parse it back again into an object... 这是一个学习练习,我们将这个JSON对象转换为字符串,然后再次将其解析回一个对象...

console.log(musicList); // prints the object in the musicList variable
var stringifiedMusic = JSON.stringify(musicList);
console.log(stringifiedMusic); // prints the string version of the musicList object

But I am not expecting the results I want, which is to add a simple incrementing ID number to each object in the array with the key of files . 但是我没有期望得到想要的结果,这是使用files键将简单的递增ID号添加到数组中的每个对象。 I believe I am not writing the reviver function properly... 我相信我没有正确编写Reviver功能...

var parsedMusic = JSON.parse(stringifiedMusic, function(key, value) {
  var idIncrementor = 0;
  var incrementorObject = [
    {id: idIncrementor}
  ];

  if (key === 'files') {
    idIncrementor++;
    return value.map(function (item, index) {
      return Object.assign({}, item, incrementorObject[index]);
    });
  }
  return value;
});

As it is now, this only seems to add the id: 0 key value pair to the first object but not the others. 现在,这似乎只是将id: 0键值对添加到第一个对象,而不是其他对象。 This must be because the if (key === 'files')... statement is only ever true just once. 这必须是因为if (key === 'files')...语句仅一次为true。 What would I check for in my if statement that would be true for the three objects in the array if I only have key and value arguments passing into the function? 如果只有keyvalue参数传入函数,我将在if语句中检查对数组中的三个对象是否正确的内容?

You don't need to create a new object. 您无需创建新对象。 The map function, if used correctly, will return a new array(with new objects). 如果正确使用map函数,将返回一个新数组(带有新对象)。 And you can use the index provided by map to get your id. 您可以使用map提供的索引来获取您的ID。

DEMO DEMO

var musicList = {
  "files": [
        {
          "title": "Ironic"
        },
        {
          "title": "It's Beginning To Look A Lot Like Christmas"
        },
        {
          "title": "Sweet Dreams"
        }
      ] 
};

var stringifiedMusic = JSON.stringify(musicList);

var parsedMusic = JSON.parse(stringifiedMusic, function(key, value) {

  if (key === 'files') {
    return value.map(function (item, index) {
      item.id = index;
      return item;
    });
  }
  return value;
});

console.log("parsedMusic", parsedMusic)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM