javascript中对象数组的比较和推送

javascript中对象数组的比较和推送,javascript,arrays,object,Javascript,Arrays,Object,阵列1: 阵列2: [{"Attribute1":"Apple","Attribute2":"jacob.nelson@cognizant.com"}] 我想将array1中“Attribute1”的值替换为array2中“Attribute1”的值。 我的输出应该是 [{"Attribute1":"orange"}]` 我不熟悉javascript。我被困在这里。任何帮助都将不胜感激。您向我们展示的是JSON对象表示 在本例中,您有一个对象数组,因此如果执行下一步操作: [{"Attri

阵列1:

阵列2:

 [{"Attribute1":"Apple","Attribute2":"jacob.nelson@cognizant.com"}]
我想将array1中“Attribute1”的值替换为array2中“Attribute1”的值。 我的输出应该是

[{"Attribute1":"orange"}]`

我不熟悉javascript。我被困在这里。任何帮助都将不胜感激。

您向我们展示的是JSON对象表示

在本例中,您有一个对象数组,因此如果执行下一步操作:

[{"Attribute1":"orange","Attribute2":"jacob.nelson@cognizant.com"}]
这表示数组中有一个对象,然后必须获取它:

>>ar=[{"Attribute1":"Apple","Attribute2":"jacob.nelson@cognizant.com"}]
[Object]
然后,如果您需要替换对象中的某些内容,则必须将它们视为对象

>>obj=ar[0]
Object {Attribute1: "Apple", Attribute2: "jacob.nelson@cognizant.com"}
就这些

提示如果有许多对象,请在其上循环:

>>ar2=[{"Attribute1":"orange"}]
>>obj2=ar2[0]
>>obj1.Attribute1=obj2.Attribute1

对于这一个案例来说,这可能是杀伤力过大了,但事实是:

使用

通过执行以下操作,可以获得所需的结果:

// adds Object.extend if it does not already exist
if (typeof Object.extend !== 'function') {
    Object.extend = function (d /* DESTINATION */, s /* SOURCE */) {
        for (var k in s) {
            if (s.hasOwnProperty(k)) {
                var v = s[k];
                if (d.hasOwnProperty(k) && typeof d[k] === "object" && typeof v === "object") {
                    Object.extend(d[k], v);
                } else {
                    d[k] = v;
                }
            }
        }
        return d;
    };
}

但就像评论中提到的那样;如果这是唯一的情况,请手动进行

如果两个数组的定义如上所述,是否要执行此操作?:array1[0]。Attribute1=array2[0]。Attribute1;没有任何函数可以为您执行此操作。您必须手动循环和比较对象。如果不明显,您应该意识到两个数组中当前只有一个项—一个包含一组成员的对象。您真的需要一个数组,还是对象就足够了?(换句话说,你是在寻找
array1[0]。Attribute1=array2[0]。Attribute1
正如@DavidFleeman所建议的,还是你真的只想要
obj1.Attribute1=obj2.Attribute1
?)通常在JavaScript中,你只需要动态对象。相关合并线程:实际上我需要的是数组而不是对象
// adds Object.extend if it does not already exist
if (typeof Object.extend !== 'function') {
    Object.extend = function (d /* DESTINATION */, s /* SOURCE */) {
        for (var k in s) {
            if (s.hasOwnProperty(k)) {
                var v = s[k];
                if (d.hasOwnProperty(k) && typeof d[k] === "object" && typeof v === "object") {
                    Object.extend(d[k], v);
                } else {
                    d[k] = v;
                }
            }
        }
        return d;
    };
}
var arr1 = [{"Attribute1":"Apple","Attribute2":"jacob.nelson@cognizant.com"}],
    arr2 = [{"Attribute1":"orange"}];
arr1 = Object.extend(arr1, arr2);
>> [{"Attribute1":"orange","Attribute2":"jacob.nelson@cognizant.com"}]