Home > Back-end >  How to join two datasets in javascript
How to join two datasets in javascript

Time:11-24

I am fairly new to javscript and this might sound like an easy question. I have two datasets that have the same column and I would like to join them together.

The datasets look sth like this:

const dataset1= [{state: 'France', value: 1001.8},
                 {state: 'Germany', value: 1236.8},..,]

const dataset2= [{state: 'France', value: 5320},
                 {state: 'Germany', value: 5670},..,]

The values on both datasets represent different things. I want to achieve sth like this:

[{state: 'France', value: 1001.8, value2: 5320},
 {state: 'Germany', value: 1236.8, value2: 5670},...]

Would really appreciate it if someone could give me a hint on how to do this!

CodePudding user response:

Same order, same keys?

const merged = dataset1.map(({state, value}, i) =>
    ({state, value, value2: dataset2[i].value}));

CodePudding user response:

let dataset1= [{state: 'France', value: 1001.8},
                 {state: 'Germany', value: 1236.8}]

let dataset2= [{state: 'France', value: 5320},
                 {state: 'Germany', value: 5670}]
let dataset3 = [];
let  i = 0;
dataset1.map((set)=>{
set1 ={...set, value2:dataset2[i].value};
dataset3.push(set1);
i  ;
})

console.log(dataset3)
  • Related