1

Let's say I have a JSON data set in the form:

{ "fruits": {
    "apple": {
        "color": red,
        "size": small
    }
    "orange": {
        "color": orange,
        "size": small
    }
}

How would I add an extra name data point (using something like JavaScript to parse the data) to each one so that they look like this:

{ "fruits": {
    "apple": {
        "color": red,
        "size": small,
        "name": apple
    }
    "orange": {
        "color": orange,
        "size": small,
        "name": orange
    }
}

I know it might seem redundant to have both an id and name value be the name of the fruit but I need this structure for the program I'm working on. Any suggestions?

ch1maera
  • 1,369
  • 5
  • 20
  • 42

1 Answers1

2

A few things first, your properties should be in quotations (unless they are variables, but I don't think that they are, ie:

"apple": {
    "color": "red",
    "size": "small"
}

And you need a comma between your two fruits.

Now all you have to do is cycle through each fruit and add a new property equal to its name:

for (var property in data.fruits) {
    if (data.fruits.hasOwnProperty(property)) {
        data.fruits[property].name = property;
    }
}

Square bracket notation allows you to access a dynamic or variable property name, which makes setting the name property fairly straight forward. See this answer for how to iterate through an array.

The snippet below demonstrates the code in action:

var data = { 
 "fruits": {
  "apple": {
   "color": "red",
   "size": "small"
     },
  "orange": {
   "color": "orange",
   "size": "small"
  }
 }
}



for (var property in data.fruits) {
    if (data.fruits.hasOwnProperty(property)) {
  data.fruits[property].name = property;
    }
}


console.log(data);
Community
  • 1
  • 1
Andrew Reid
  • 37,021
  • 7
  • 64
  • 83