替换对象中的值

时间:2016-06-10 09:58:38

标签: arrays javascript-objects

我有一个看起来像这样的对象:

{id: 1, cells: ["Ashar", 68345, 14, 66666, "Retail", 1, ""]}

我有一组像这样的对象:

[
 {id: 1, cells: ["Ashar", 68345, 14, 46100, "Retail", 1, ""]}, 
 {id: 2, cells: ["Ashar", 300881, 14, 37000, "Retail", 3, 3]}, 
 {id: 3, cells: ["Rob", 94448, 17, 11395, "Retail", 1, ""]}, 
 {id: 4, cells: ["Shahab", 19023870, 219, 12500, "Retail", 1, ""]}, 
 {id: 5, cells: ["David", 29008000, 229, 12500, "Retail", 5, 26]}
]

我要做的是获取第一个对象的id并使用它来搜索数组以找到匹配的id,然后将cells的值替换为第一个对象的值。 / p>

任何帮助解决这个问题都会非常感激。

感谢您的时间。

1 个答案:

答案 0 :(得分:1)

var temp = {id: 1, cells: ["Ashar", 68345, 14, 66666, "Retail", 1, ""]};

var arr=[
 {id: 1, cells: ["Ashar", 68345, 14, 46100, "Retail", 1, ""]}, 
 {id: 2, cells: ["Ashar", 300881, 14, 37000, "Retail", 3, 3]}, 
 {id: 3, cells: ["Rob", 94448, 17, 11395, "Retail", 1, ""]}, 
 {id: 4, cells: ["Shahab", 19023870, 219, 12500, "Retail", 1, ""]}, 
 {id: 5, cells: ["David", 29008000, 229, 12500, "Retail", 5, 26]}
];    
arr.forEach(function(value,key){
    if(value.id == temp.id) {
           value.cells=temp.cells;
    }
});