当我在同一对象中具有另一个属性的值时,从对象数组中获取Object属性
Get a Object property from array of objects when I have the value of another property in the same object
在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 2
的itemsArray[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(),可能非常有趣和有用。特别是如果你用这个问题来更好地理解数组或编程,我建议你学习如何全部使用它们。
相关文章:
- 为什么我可以在Array属性对象中找到Javascript Array for Each方法
- 使用onclick调用属性对象函数
- 嵌套为..in 循环,列出多维对象的属性(对象)
- 动态属性对象 - JSON
- 在不使用隔离范围angularjs自定义指令的情况下获取属性对象
- 通过属性传递属性/对象.Javascript
- Javascript:属性/对象的类型
- 访问JSON中的属性(对象)
- 属性对象Javascript不是用Jquery Deferred设置的
- 无法读取属性'#<对象>'未定义的获取错误
- Twitter中多属性对象的子字符串匹配
- 无法设置'data'属性'对象'标记.(只IE8)
- 更新数据属性对象属性值
- 将属性对象的选定对象从原型推入数组
- 将单个属性对象字面量的数组转换为仅包含其值的数组的最佳方法
- 寻找一种更简单的方法来检查是否多个属性&对象中的方法是未定义的
- 主干模型:带有get方法的空属性,但在属性对象中
- 如何赋值给"text"someText"属性对象在动能js
- Angularjs的数据绑定与数据属性对象
- 如何将一个嵌套的javascript对象转换为只有一级属性对象