简体   繁体   English

Map 两个 arrays typescript

[英]Map two arrays in typescript

I have two arrays The first array我有两个 arrays 第一个数组

{
    "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我可以使用map function 来匹配第一个数组的键和第二个数组的 ID 以获得这样的结果数组吗

[
{
 "label": "poids",
 "value": 82,
 "description": "le poids"
},
{
 "label": "taille",
 "value": 78,
 "description": "la taille"
},
{
 "label": "ratio coeur",
 "value": 27,
 "description": "le ratio coeur"
},
]

MGX is correct. MGX是正确的。 Your first item is not an array but an object.您的第一项不是数组,而是 object。

This is what you got to do, to make it work with an object.这是你必须做的,让它与 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:或者,您可以将valueObject转换为Map以更轻松地获得结果:

const map = new Map(Object.entries(valueObject));

const result = array.map((item) => { 
  return {
    label: item.label,
    value: map.get(item.id),
    description: item.description,
  };
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM