使用公共密钥更新javascript数组

时间:2018-07-10 18:11:22

标签: javascript arrays

我有2个具有以下内容的javascript数组:

Array1:

[{"key":"Agents"},{"key":"Formal"},{"key":"Annotation"},{"key":"Business"}]

Array2:

[
    {"key":"Agents","class":"newclass","text":"Agents"}, 
    {"key":"Business","class":"newclass1","text":"Business"},
    {"key":"Formal","class":"newclass2","text":"Formal"},
    {"key":"Annotation","class":"class5","text":"Annotation"},
    {"key":"Rate","class":"newclass1","text":"Rates"}
]

两个数组中的键相同。我想通过匹配键从 array2 中使用classtext values更新 array1 。 有没有一种方法可以不迭代两个数组?这只是阵列的一小部分。实际可能会大一些。

2 个答案:

答案 0 :(得分:0)

不幸的是,您需要遍历两个数组才能在每个数组中找到正确的对象。即使使用内置的js原型方法,您也将遍历整个数组。

您可以解决此问题的一种方法是修改数据结构。而不是使用字典数组,而是像这样制作字典字典:

第一个数组:

{
    "Agents": {},
    "Business": {},
    "Formal": {},
    "Annotation": {},
    "Rate": {}
}

第二个数组:

{
    "Agents": {
        "class": "newclass",
        "text": "Agents"
    },
    "Business": {
        "class": "newclass1",
        "text": "Business"
    },
    "Formal": {
        "class": "newclass2",
        "text": "Formal"
    },
    "Annotation": {
        "class": "newclass5",
        "text": "Annotation"
    },
    "Rate": {
        "class": "newclass1",
        "text": "Rates"
    }
}

现在,您可以执行类似Array1["Agents"] = Array2["Agents"]的操作,也可以添加数据。

答案 1 :(得分:0)

如果需要新对象,则可以复制属性,但是看起来数组一只是数组二的过滤器集-您可以将第一个映射到每个对应的第二个。不可避免地要遍历两个数组,但是您始终可以创建一个map / ID缓存,这样就只能对每个数组进行一次遍历。

const arr1 = [
    {"key": "Agents"},
    {"key": "Formal"},
    {"key": "Annotation"},
    {"key": "Business"}
]

const arr2 = [
    {"key": "Agents", "class": "newclass", "text": "Agents"}, 
    {"key": "Business", "class": "newclass1", "text": "Business"},
    {"key": "Formal", "class": "newclass2", "text": "Formal"},
    {"key": "Annotation", "class": "class5", "text": "Annotation"},
    {"key": "Rate", "class": "newclass1", "text": "Rates"}
]

const transformer = from => {
    const cache = from.reduce((map, item) => (
        map[item.key] = item, map
    ), {})
    return ({ key }) => cache[key]
}

console.log(
    arr1.map(transformer(arr2))
)