Reputation: 2933
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
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