Been scratching my head on this one for an entire evening with no solution in sight.
Put simply
I am querying two arrays from two separate APIs.
They return data in following format:
API 1
JavaScript
x
16
16
1
[{
2
balance: 4444,
3
age: "18",
4
gender: "Male",
5
level: "2",
6
name: "Joe"
7
8
}, {
9
balance: 3333,
10
age: "45",
11
gender: "Male",
12
level: "3",
13
name: "Angel"
14
}
15
}]
16
API 2
JavaScript
1
9
1
{
2
Joe: {
3
score: 32
4
},
5
Angel: {
6
score: 22
7
}
8
}
9
I need to match the object keys from the second API to the name value of playerInfo from first API so a new array is made that is completely flat like this:
JavaScript
1
18
18
1
[{
2
balance: 4444,
3
age: "18",
4
gender: "Male",
5
level: "2",
6
name: "Joe",
7
score: 32
8
9
}, {
10
balance: 3333,
11
age: "45",
12
gender: "Male",
13
level: "3",
14
name: "Angel",
15
score: 22
16
}
17
}]
18
Here’s where I am being stone walled at the moment
JavaScript
1
18
18
1
var result = []
2
3
const matchKeys = (data, data1) => {
4
let arr = []
5
arr.push(data1)
6
7
data.map(item => {
8
arr.map(item1 => {
9
if (item.name === Object.keys(item1)) {
10
result.push(Object.assign(item, item1))
11
console.log(result)
12
}
13
})
14
})
15
}
16
17
matchKeys(api1, api2)
18
I suspect I’m not getting very far because I am not properly accessing my second dataset because there is no index that keeps track of which object I am supposed to pair up with corresponding value in the arrays.
Appreciate any help
Advertisement
Answer
You can implement that using Array.map
.
JavaScript
1
34
34
1
const input1 = [{
2
balance: 4444,
3
age: "18",
4
gender: "Male",
5
level: "2",
6
name: "Joe"
7
}, {
8
balance: 3333,
9
age: "45",
10
gender: "Male",
11
level: "3",
12
name: "Angel"
13
}];
14
15
const input2 = {
16
Joe: {
17
score: 32
18
},
19
Angel: {
20
score: 22
21
}
22
}
23
24
function matchKeys(arr1, arr2) {
25
const result = arr1.map((item) => {
26
if (input2[item.name]) {
27
return { item, input2[item.name] };
28
}
29
return item;
30
});
31
return result;
32
}
33
34
console.log(matchKeys(input1, input2));