我有一个数组:
myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}, etc.]
我无法更改阵列的结构。我收到了一个45的id,我想得到数组中该对象的“bar”。
如何在JavaScript或使用jQuery实现这一点?
我有一个数组:
myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}, etc.]
我无法更改阵列的结构。我收到了一个45的id,我想得到数组中该对象的“bar”。
如何在JavaScript或使用jQuery实现这一点?
当前回答
使用Array.prototype.filter()函数。
演示:https://jsfiddle.net/sumitridhal/r0cz0w5o/4/
JSON
var jsonObj =[
{
"name": "Me",
"info": {
"age": "15",
"favColor": "Green",
"pets": true
}
},
{
"name": "Alex",
"info": {
"age": "16",
"favColor": "orange",
"pets": false
}
},
{
"name": "Kyle",
"info": {
"age": "15",
"favColor": "Blue",
"pets": false
}
}
];
过滤器
var getPerson = function(name){
return jsonObj.filter(function(obj) {
return obj.name === name;
});
}
其他回答
查找数组索引的方法:
index = myArray.map((i) => i.id).indexOf(value_of_id);
item = myArray[index];
最短,
var theAnswerObj = _.findWhere(array, {id : 42});
下面的代码将帮助您从数据中的嵌套对象中搜索值。
const updatedData = myArrayOfObjects.filter((obj: any) => Object.values(obj).some((val: any) => {
if (typeof (val) == typeof ("str")) {
return val.toString().includes(Search)
} else {
return Object.values(val).some((newval: any) => {
if (newval !== null) {
return newval.toString().includes(Search)
}
})
}
}))
我认为最简单的方法是以下方法,但它在Internet Explorer 8(或更早版本)上不起作用:
var result = myArray.filter(function(v) {
return v.id === '45'; // Filter out the appropriate one
})[0].foo; // Get result and access the foo property
尝试以下操作
function findById(source, id) {
for (var i = 0; i < source.length; i++) {
if (source[i].id === id) {
return source[i];
}
}
throw "Couldn't find object with id: " + id;
}