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

Get a Object property from array of objects when I have the value of another property in the same object

本文关键字:属性 对象 Object 获取 数组 另一个      更新时间:2023-09-26

在JavaScript中,如果变量中有这个值。。。

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',
    },
]; 

如何从值selectedId所具有的对象中获取itemsArray name值。

在这个例子中,我在selectedId中有2的值,并且需要得到Item 2itemsArray[n][name]

你可以像这个一样使用.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);

这可能是您所需要的:

// 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(),可能非常有趣和有用。特别是如果你用这个问题来更好地理解数组或编程,我建议你学习如何全部使用它们。