在Javascript中将对象添加到列表

时间:2017-02-07 08:11:29

标签: javascript

我给出了以下数据:

参考清单:

[{
    name: "dog", present: false
}, {
    name: "cat", present: true
}, {
    name: "bird", present: false
}]

鉴于列表:

["dog, cat"]

通缉结果:

[{
    name: "dog", present: true
}, {
    name: "cat", present: true
}, {
    name: "bird", present: false
}]

现在我可以通过创建3条条件语句并执行indexOf来生成通缉结果。但是,我想知道是否有办法通过lodash这样的方式完成所有这一切。

6 个答案:

答案 0 :(得分:3)

这就是你需要的吗?

let reference = [{name:"dog", present:false}, {name:"cat", present:true}, {name:"bird", present:false }];
let list = ['dog', 'cat'];

let result = reference.map(item => ({
  name: item.name,
  present: list.indexOf(item.name) !== -1
}));

console.log(result);

它在逻辑上与您所写的相同,只是使用.map函数。

答案 1 :(得分:1)

使用Array.prototype.forEach()Array.prototype.indexOf()函数的最短解决方案:



var data = [{ name: "dog", present: false }, { name: "cat", present: true }, { name: "bird", present: false }],
    f = ["dog", "cat"];

data.forEach(function (o) { o.present = (f.indexOf(o.name) !== -1); });
console.log(data);




答案 2 :(得分:0)

您可以使用Array.map()



var reflist = [{
  name: "dog",
  present: false
}, {
  name: "cat",
  present: true
}, {
  name: "bird",
  present: false
}];

var givenList = ["dog", "cat"];

reflist = reflist.map(function(elem){
  if(givenList.indexOf(elem.name) !== -1)
    elem.present = true; 
  return elem;
});

console.log(reflist);




答案 3 :(得分:0)

另一种方法。



var fields = [{
  name: "dog", present: false
}, {
  name: "cat", present: true
}, {
  name: "bird", present: false
}];

console.log(fields);

['dog', 'cat'].forEach(function (value) {
  fields.forEach(function (k) {
    if (k.name === value) {
      k.present = true;
    }
  });
});

console.log(fields);




答案 4 :(得分:0)

您需要循环参考数据的项目,将每个项目与给定的项目集进行比较,并构建一个新的对象数组。

var wantedResult = [];
var keys = Object.keys(refData);
for(var i=0; i<keys.length; i++) {
    wantedResult.push({
        name:refData[keys[i]].name,         
        present:givenList.indexOf(refData[keys[i]].name) != -1
    });
}

答案 5 :(得分:0)

这是你的单行:

referenceList.map((e) => { e.present = givenList.indexOf(e.name) > -1;})

请注意,您将修改referenceList,此行的返回值对您没用。它只是undefined

的列表

Reference