0

Say i have the following json array

[ { 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' }    ]

And i know the title of the element i want to update. For this example, i wish to add a 'description' element to the element with title: 'Test'. I have the entire item where the title is {...} stored, so i can access the title from there, but i was wondering how to add an element to this specific item.

Apologies if ive used any incorrect terminology, pretty new to json. Any help would be much appreciated.

Ryan Turnbull
  • 3,766
  • 1
  • 25
  • 35
  • That's not [JSON](http://json.org). _"JSON is a textual, language-indepedent data-exchange format, much like XML, CSV or YAML."_ -> [What is the difference between JSON and Object Literal Notation?](https://stackoverflow.com/questions/2904131/what-is-the-difference-between-json-and-object-literal-notation) – Andreas Jul 15 '17 at 09:07

2 Answers2

2

You can use the Array.find() method to get the item you want. Then set the description for that item, which will update the item in the array since it's a reference.

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);
H77
  • 5,859
  • 2
  • 26
  • 39
  • That is what the line `testItem.description = "test description";` does. If you run the snippet you will see that the array has been updated. – H77 Jul 15 '17 at 09:08
0

try this with for of

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);
H77
  • 5,859
  • 2
  • 26
  • 39
Arun Kumaresh
  • 6,211
  • 6
  • 32
  • 50