Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Merge a simple array of values into an array of json by adding a key

Good morning,
I’m struggling with a small problem, and I don’t find an answer for my case :

I have an array of value : let’s say

let tab = [1,2,3]

Then I have an array of json :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

let values = [
  {key1 : "a", key2 : "b", key3: "c"}, 
  {key1 : "d", key2 : "e", key3: "f"},
  {key1 : "g", key2 : "h", key3: "i"}
]

I would like to map the value of the array in the json to have :

[{key1 : "a", key2 : "b", key3: "c", index: 1}, 
{key1 : "d", key2 : "e", key3: "f", index: 2},
{key1 : "g", key2 : "h", key3: "i", index: 3}]

Is there an easy to do that ?

>Solution :

Assuming you meant "array of objects" and not "array of json", you can indeed do it with map this way:

const tab = [1,2,3]

const myArray = [
{key1: 'a', key2: 'b', key3:'c'}, 
{key1:'d', key2 : 'e', key3:'f'},
{key1 : 'g', key2 : 'h', key3:'i'}];

console.log(myArray.map((element, index) => { return {...element, index:tab[index]}; }));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading