0

Essentially I have some data like this:

[
 {
  "Forename": "Scott",
  "Surname": "Jones",
  "Age": 18,
 },
 {
  "Forename": "Tina",
  "Surname": "Turner",
  "Age": 20,
 },
 {
  "Forename": "Joe",
  "Surname": "Bloggs",
  "Age": 20,
 }
]

I want to know how to add in a key value pair using javascript like so:

[
 {
  "id": 1,
  "Forename": "Scott",
  "Surname": "Jones",
  "Age": 18,
 },
 {
  "id": 2,
  "Forename": "Tina",
  "Surname": "Turner",
  "Age": 20,
 },
 {
  "id": 3,
  "Forename": "Joe",
  "Surname": "Bloggs",
  "Age": 20,
 }
]

I was looking at stuff like mapping through the and adding it to each object but that seemed to only let me add a key value pair to the end of each one.

Any help / guidance appreciated!

  • _"stuff like mapping"_ may you share that code? – evolutionxbox Feb 28 '20 at 14:52
  • jsonObj.map(i => i.id = "1"); thats how i was appending to the end of each object – eversosarky Feb 28 '20 at 14:59
  • You need to return the new item, not mutate it. `map(i => ({ id = "1", ...i }) );` – evolutionxbox Feb 28 '20 at 15:01
  • 1
    Notice that while others may propose workarounds, the fields of a JSON object are not intended to have an order (https://www.json.org/json-en.html). "An object is an unordered set of name/value pairs.". Depending what you do with the object, it will keep the order, put it in alphabetical order, etc.. – E. Zacarias Feb 28 '20 at 15:03

4 Answers4

1

The fastest way to do this I can think of is :

let data = [
 {
  "Forename": "Scott",
  "Surname": "Jones",
  "Age": 18,
 },
 {
  "Forename": "Tina",
  "Surname": "Turner",
  "Age": 20,
 },
 {
  "Forename": "Joe",
  "Surname": "Bloggs",
  "Age": 20,
 }
];

data = data.map((e,i) => Object.assign({id: i}, e));
YounesM
  • 2,111
  • 11
  • 27
0

if you have an array and want to iterate through it, you can use functional methods like forEach or map

var id = 0;
const array = [
 {
  "Forename": "Scott",
  "Surname": "Jones",
  "Age": 18,
 },
 {
  "Forename": "Tina",
  "Surname": "Turner",
  "Age": 20,
 },
 {
  "Forename": "Joe",
  "Surname": "Bloggs",
  "Age": 20,
 }
]
array.forEach((elm) => elm.id = id++)

Anyway your id property is appended at the end because in javascript the order of the properties of objects is not always guaranteed to be maintained. Take a look at this question

asdru
  • 895
  • 7
  • 15
0

The non-numeric keys in a javascript object are ordered by when they are added, so adding a key in a map will place it at the bottom. If you want your key to be positioned higher (it honestly should not matter), you would need to create a new object from your existing one.

We can do that with a function sort of like this:

const obj = {
  "id": 1,
  "Surname": "Jones",
  "Age": 18,
 };

function objectInsertAt(object, position, key, value) {
   let i = 0;
   let result = {};
   
   for (let prop in object) {
       if (object.hasOwnProperty(prop)) {
           console.log(prop + ' - ' + i);
           if (position === i) {
               result[key] = value;
           }
           
           result[prop] = object[prop];
       }
       
       i++;
   }
   
   return result;
}

const newObj = objectInsertAt(obj, 2, 'Forename', 'Scott');
console.log(newObj);

You can read more about the traversal order of object keys here: https://2ality.com/2015/10/property-traversal-order-es6.html#traversing-the-own-keys-of-an-object

The summary of that article is:

Property keys are traversed in the following order:

  • First, the keys that are integer indices (what these are is explained later), in ascending numeric order.
  • Then, all other string keys, in the order in which they were added to the object.
  • Lastly, all symbol keys, in the order in which they were added to the object.

Many engines treat integer indices specially (even though they are still strings, at least as far as the ES6 spec is concerned). Therefore, it makes sense to treat them as a separate category of keys.

Community
  • 1
  • 1
Jeremy Harris
  • 23,007
  • 13
  • 73
  • 124
0

You can use map

    const array = [ { "Forename": "Scott", "Surname": "Jones", "Age": 18, }, { "Forename": "Tina", "Surname": "Turner", "Age": 20, }, { "Forename": "Joe", "Surname": "Bloggs", "Age": 20, } ]
    const updatedArray = array.map((data,id) => ({...data, id}));

Raj Kumar
  • 693
  • 6
  • 12