简体   繁体   中英

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:

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...

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 . I believe I am not writing the reviver function properly...

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. This must be because the if (key === 'files')... statement is only ever true just once. 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?

You don't need to create a new object. The map function, if used correctly, will return a new array(with new objects). And you can use the index provided by map to get your id.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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