Issue
I have two arrays The first array
{
"heart_rate": 27,
"height": 82,
"weight":78
}
The second array
[
{
"id": "heart_rate",
"description": "le ratio coeur",
"label":"ratio coeur"
},
{
"id": "height",
"label": "taille",
"description": "la taille"
},
{
"id": "weight",
"label": "poids",
"description": "le poids"
}
]
can I use map
function to match the key of the first array and the id of the second array in order to get a result array like this
[
{
"label": "poids",
"value": 82,
"description": "le poids"
},
{
"label": "taille",
"value": 78,
"description": "la taille"
},
{
"label": "ratio coeur",
"value": 27,
"description": "le ratio coeur"
},
]
Solution
MGX is correct. Your first item is not an array but an object.
This is what you got to do, to make it work with an object.
const valueObject = {
"heart_rate": 27,
"height": 82,
"weight":78
};
const array = [
{
"id": "heart_rate",
"description": "le ratio coeur",
"label":"ratio coeur"
},
{
"id": "height",
"label": "taille",
"description": "la taille"
},
{
"id": "weight",
"label": "poids",
"description": "le poids"
}
]
const keys = Object.keys(valueObject);
const values = Object.values(valueObject);
const result = array.map((item) => {
return {
label: item.label,
value: values[keys.findIndex(key => key === item.id)],
description: item.description,
};
});
Alternatively you can convert your valueObject
to a Map
to get the result easier:
const map = new Map(Object.entries(valueObject));
const result = array.map((item) => {
return {
label: item.label,
value: map.get(item.id),
description: item.description,
};
});
Answered By - Alexander Belokon
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.