PlayHardGoPro
PlayHardGoPro

Reputation: 2933

How to add a new pair of (key,value) to every subarray of a javascript object?

Let's imagine that I have a Json like this:

{
   0: {
      id: "1",
      usr: "pimba"
   },
   1: {
      id: "2",
      usr: "aloha"
   },
   ...
   100: {
      id: "3",
      usr: "pruu"
   }
}

I need to add a new (key,value) pair for EVERY subArray. Is it possible without using foreach ? Maybe some sort of function that already apply a certain fucntion to every subarray ?
I need to add the (key: value) after usr: value.

OBS: The set (key,value) that I want to add, in this case, will always be the same.

The result I need:

{
   0: {
      id: "1",
      usr: "pimba"
      synced: true
   },
   1: {
      id: "2",
      usr: "aloha"
      synced: true
   },
   ...
   100: {
      id: "3",
      usr: "pruu"
      synced: true
   }
}

Upvotes: 0

Views: 463

Answers (1)

tonkatata
tonkatata

Reputation: 509

What about this:

let a = {
    0: {
       id: "1",
       usr: "pimba"
    },
    1: {
       id: "2",
       usr: "aloha"
    },
    3: {
       id: "3",
       usr: "pruu"
    }
 }

 let b = Object.values(a).map(newKeyValue => {
    newKeyValue.newKey = "newValue"
    console.log(newKeyValue)
 })

First of all, what you call an "array" is actually an "object".

And objects have two very very cool methods.

Object.keys returns an array of all keys of the object.

Object.values returns an array of all values of the object.

Upvotes: 2

Related Questions