如何使用Javascript按键值将新值插入数组

时间:2016-09-29 06:14:23

标签: javascript arrays

我需要一个帮助。我需要通过使用Javascript匹配键值将一个新值插入现有数组。我正在解释下面的场景。

var galArr=[
     {'image':'12.png','comment':'hii','act':'edit'},
     {'image':'13.png','comment':'hello','act':'edit'},
     {'image':'14.png','comment':'hee','act':'edit'},
]

以上是我现有的数组。我需要与下面的另一个数组匹配。

var arr=[
    {'image':'12.png','comment':'hii'},
    {'image':'14.png','comment':'hee'},
]

这里我需要将数组arr与数组galArr匹配,如果图像名称相同,则此checked:true将添加到现有数组galArr的重复行中。假设arr[0].image==galArr[0].image然后checked:true将添加到现有数组的相应行中。请帮帮我。

3 个答案:

答案 0 :(得分:1)

这应该足够了。



var galArr=[
     {'image':'12.png','comment':'hii','act':'edit'},
     {'image':'13.png','comment':'hello','act':'edit'},
     {'image':'14.png','comment':'hee','act':'edit'},
];
var arr=[
    {'image':'12.png','comment':'hii'},
    {'image':'14.png','comment':'hee'},
];

// start looping over `arr`
arr.forEach(function(o, i){
   
  // now loop over `galArr` to find match
  galArr.forEach(function(gO, i){
      // when there is a match
      if(o.image == gO.image){
         console.log(gO);
         // add checked property to this object
         gO['checked'] = true;
      }
  });
  
});

// Output
console.log(galArr);




答案 1 :(得分:0)

首先检查条件,如果条件匹配,则创建一个新的临时json并将其替换为旧的json

 arr.forEach(function(d){
       galArr.forEach(function(e){
            if(e.image==d.image){
               temp = {};
               temp.image = e.image;
               temp.comment = e.comment;
               temp.checked = e.comment;
               temp.action = e.action;
               e = temp;
            }
       });
    });

答案 2 :(得分:0)

我会创建一个图像索引,其索引将是整个图像文件名,稍后我会使用该图像索引快速检查并将checked属性添加到galArr数组:

var galArr=[
     {'image':'12.png','comment':'hii','act':'edit'},
     {'image':'13.png','comment':'hello','act':'edit'},
     {'image':'14.png','comment':'hee','act':'edit'},
];
  
var imageIndex = galArr.map(function(item) {
    return item.image;
});

var arr=[
    {'image':'12.png','comment':'hii'},
    {'image':'14.png','comment':'hee'},
]

arr.forEach(function(item) {
    item.checked = imageIndex.indexOf(item.image) > -1;
});

如果您的用户将在现代Web浏览器中使用您的JavaScript代码,我会使用新的Set collection

var galArr=[
     {'image':'12.png','comment':'hii','act':'edit'},
     {'image':'13.png','comment':'hello','act':'edit'},
     {'image':'14.png','comment':'hee','act':'edit'},
];
  
var imageIndex = galArr.reduce(function(result, item) {
    result.add(item.image);
 
    return result;
}, new Set());

var arr=[
    {'image':'12.png','comment':'hii'},
    {'image':'14.png','comment':'hee'},
]

arr.forEach(function(item) {
    item.checked = imageIndex.has(item.image);
});

我已经提出了一个问题,以帮助每个人了解的价值:Is Set a hashed collection in JavaScript?