循环遍历一个对象数组,只获得几个对象

时间:2016-07-27 19:36:42

标签: javascript arrays loops object underscore.js

我有以下对象数组。

[Object, Object, Object]
    0:Object
       name: "Rick"
       Contact: "Yes"
       id: 1
    1:Object
       name:"Anjie"
       Contact:"No"
       id: 2
    2:Object
       name:"dillan"
       Contact:"Maybe"
       id:3

现在,我只想要名称和联系人对象。我怎么能得到它。另外,在其他情况下,我想要名字和身份证明。有人可以告诉我如何实现这一目标。

例如只有姓名和联系方式才能给出这个结果。

[Object, Object, Object]
    0:Object
      name: "Rick"
      Contact: "Yes"
    1:Object
      name:"Anjie"
      Contact:"No"
    2:Object
      name:"dillan"
      Contact:"Maybe"

5 个答案:

答案 0 :(得分:1)

最简单的方法是使用map函数:

var objs = objs.map(function(obj) {
    return {
        name: obj.name,
        Contact: obj.Contact
    }
});

或者,您可以手动循环:



var objs = [{
       name: "Rick",
       Contact: "Yes",
       id: 1
}, {
       name:"Anjie",
       Contact:"No",
       id: 2
}, {
       name:"dillan",
       Contact:"Maybe",
       id:3
}];

var newObjs = [];

for ( var i=0, len = objs.length; i < len; i++ )
{
    newObjs.push({
        name: objs[i].name,
        Contact: objs[i].Contact
    });
}

console.log(newObjs);
&#13;
&#13;
&#13;

答案 1 :(得分:1)

如果你想访问数组中对象的某些属性,你可以使用for循环并传递i的值,如: -

ActionView::Base.field_error_proc = proc { |input, instance| "#{input}".html_safe }

或者只是编写一个函数,使其与数组中的对象形成单独的对象。

答案 2 :(得分:1)

您可以使用下划线的mappick

var result = _.map(data, item => _.pick(item, 'name', 'Contact'));  

答案 3 :(得分:1)

通用解决方案可以是具有给定数据数组和密钥数组的解决方案。想要的属性映射到一个新数组中。

function getWithKeys(array, keys) {
    return array.map(function (a) {
        var o = {};
        keys.forEach(function (k) {
            o[k] = a[k];
        });
        return o;
    });
}

var array1 = [{ name: "Rick", Contact: "Yes", id: 1 }, { name: "Anjie", Contact: "No", id: 2 }, { name: "dillan", Contact: "Maybe", id: 3 }],
    array2 = getWithKeys(array1, ['name', 'Contact']),
    array3 = getWithKeys(array1, ['name', 'id']);

console.log(array2);
console.log(array3);

答案 4 :(得分:0)

您可以使用map()并返回已删除属性的新对象数组。要创建对象副本,您可以使用(JSON.parse(JSON.stringify()))

var data = [{ id: 1, name: "Rick", Contact: "Yes" }, { id: 2, name: "Anjie", Contact: "No" }, { id: 3, name: "dillan", Contact: 'Maybe' }];

var result = data.map(function(e) {
  var r = (JSON.parse(JSON.stringify(e)));
  delete r.id;
  return r;
});

console.log(result)
console.log(data)

或者您使用Object.assign({}, e)

var data = [{ id: 1, name: "Rick", Contact: "Yes" }, { id: 2, name: "Anjie", Contact: "No" }, { id: 3, name: "dillan", Contact: 'Maybe' }];

var result = data.map(function(e) {
  var r = Object.assign({}, e);
  delete r.id;
  return r;
});

console.log(result);
console.log(data);