在javascript中将对象数组复制到另一个数组中 [英] Copying an array of objects into another array in javascript

查看:83
本文介绍了在javascript中将对象数组复制到另一个数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将数组的每个元素(其中元素是对象)复制到另一个数组中,使它们完全独立?我不想改变一个数组中的一个元素来影响另一个.

How can I copy every element of an array (where the elements are objects), into another array, so that they are totally independent? I don't want changing an element in one array to affect the other.

推荐答案

这里的关键是

  1. 数组中的条目是对象,并且
  2. 您不希望对一个数组中的对象的修改显示在另一个数组中.

这意味着我们不仅需要将对象复制到新数组(或目标数组),还需要创建对象的副本.

That means we need to not just copy the objects to a new array (or a target array), but also create copies of the objects.

...使用 map 创建一个新数组,然后复制对象:

...use map to create a new array, and copy the objects as you go:

const newArray = sourceArray.map(obj => /*...create and return copy of `obj`...*/);

...复制操作是您喜欢复制对象的任何方式,根据用例的不同,项目之间的差异很大.这个问题.但是例如,如果您只想复制对象而不是其属性引用的任何对象,则可以使用扩展符号(ES2015+):

...where the copy operation is whatever way you prefer to copy objects, which varies tremendously project to project based on use case. That topic is covered in depth in the answers to this question. But for instance, if you only want to copy the objects but not any objects their properties refer to, you could use spread notation (ES2015+):

const newArray = sourceArray.map(obj => ({...obj}));

这会对每个对象(和数组)进行浅拷贝.同样,对于深层副本,请参阅上面链接的问题的答案.

That does a shallow copy of each object (and of the array). Again, for deep copies, see the answers to the question linked above.

这是一个使用不尝试处理边缘情况的简单形式的深度复制的示例,请参阅边缘情况的链接问题:

Here's an example using a naive form of deep copy that doesn't try to handle edge cases, see that linked question for edge cases:

function naiveDeepCopy(obj) {
    const newObj = {};
    for (const key of Object.getOwnPropertyNames(obj)) {
        const value = obj[key];
        if (value && typeof value === "object") {
            newObj[key] = {...value};
        } else {
            newObj[key] = value;
        }
    }
    return newObj;
}
const sourceArray = [
    {
        name: "joe",
        address: {
            line1: "1 Manor Road",
            line2: "Somewhere",
            city: "St Louis",
            state: "Missouri",
            country: "USA",
        },
    },
    {
        name: "mohammed",
        address: {
            line1: "1 Kings Road",
            city: "London",
            country: "UK",
        },
    },
    {
        name: "shu-yo",
    },
];
const newArray = sourceArray.map(naiveDeepCopy);
// Modify the first one and its sub-object
newArray[0].name = newArray[0].name.toLocaleUpperCase();
newArray[0].address.country = "United States of America";
console.log("Original:", sourceArray);
console.log("Copy:", newArray);

.as-console-wrapper {
    max-height: 100% !important;
}

...并且您想将源数组的内容附加到它,您可以使用 push 和一个循环:

...and you want to append the contents of the source array to it, you can use push and a loop:

for (const obj of sourceArray) {
    destinationArray.push(copy(obj));
}

有时人们真的想要一个一个班轮",即使没有特别的原因.如果您引用它,您可以创建一个新数组,然后使用扩展符号将其扩展为单个 push 调用:

Sometimes people really want a "one liner," even if there's no particular reason for it. If you refer that, you could create a new array and then use spread notation to expand it into a single push call:

destinationArray.push(...sourceArray.map(obj => copy(obj)));

这篇关于在javascript中将对象数组复制到另一个数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆