当我在同一对象中具有另一个属性的值时,从对象数组中获取Object属性

时间:2015-10-29 20:12:17

标签: javascript

在JavaScript中如果我在变量中有这个值......

git-config

我下面有这些对象......

var selectedId = '2';

如何从值var itemsArray = [ { id: 1, name: 'Item 1', }, { id: 2, name: 'Item 2', }, { id: 3, name: 'Item 3', }, { id: 4, name: 'Item 4', }, ]; 具有的对象中获取itemsArray name值。

在此示例中,我selectedId的值为2,需要获取selectedId的{​​{1}}

2 个答案:

答案 0 :(得分:4)

您可以像这样使用.filter



var selectedId = 2;

var itemsArray = [
    {
        id: 1,
        name: 'Item 1',
    },
    {
        id: 2,
        name: 'Item 2',
    },
    {
        id: 3,
        name: 'Item 3',
    },
    {
        id: 4,
        name: 'Item 4',
    },
]; 
  
var result = itemsArray.filter(function (el) {
  return el.id === selectedId;
});
var name = result[0] && result[0].name;
console.log(name);




答案 1 :(得分:1)

这可能就是您所需要的:

// Give me everything in itemsArray where:
itemsArray.filter(function(item){

    // its id is the one I'm looking for,
    return (item.id === selectedId) 

// and give them to me in this form:
}).map(function(element){ 

    // just the name
    return element.name 
})

map()和filter()以及reduce()和forEach()可以非常有趣和有用。特别是如果您正在使用此问题来更好地理解数组或编程,我建议您学习如何使用它们。

相关问题