提问人:London28 提问时间:11/15/2023 更新时间:11/15/2023 访问量:89
使用 Javascript 遍历 JSON 对象并返回匹配条件的索引
Use Javascript to loop through an JSON object and return the indexes of the matching criteria
问:
我找到了这个半回答我的问题的先前答案,但我想返回它们出现的索引数组 - 在这种情况下,** 18A38** 将返回位置 [1,3]。
条目只是一个示例,最终版本可能会有数百个条目。
const checkArray = ['18A38']
const dataOject =
[ { id:'853K83', isGo:false }
, { id:'18A38', isGo:true }
, { id:'97T223', isGo:true }
, { id:'18A38', isGo:false }
, { id:'182B92', isGo:true }
];
const result = checkArray.map(val=>dataOject.findIndex(el=>el.id===val) )
console.log( JSON.stringify(result))
答:
1赞
Miles Acq
11/15/2023
#1
只需循环并将所需的索引推送到数组上即可
const checkArray = ['18A38']
const dataOject =
[ { id:'853K83', isGo:false }
, { id:'18A38', isGo:true }
, { id:'97T223', isGo:true }
, { id:'18A38', isGo:false }
, { id:'182B92', isGo:true }
];
let foundIndices = []
for (let i = 0; i < dataOject.length; i++) {
if (dataOject[i].id === checkArray[0]) {
foundIndicies.push(i)
}
}
return foundIndices
0赞
Tal Rofe
11/15/2023
#2
checkArray
数组的长度为 1。当然,使用后,您只能获得一个值。map
我会这样做:
const checkArray = ['18A38']
const dataOject =
[ { id:'853K83', isGo:false }
, { id:'18A38', isGo:true }
, { id:'97T223', isGo:true }
, { id:'18A38', isGo:false }
, { id:'182B92', isGo:true }
];
const result = dataOject.reduce((final, value, index) => {
if (value.id === checkArray[0]) {
return [...final, index];
}
return final;
}, []);
console.log(result);
如果可能具有更多价值,您还可以执行以下操作:checkArray
const checkArray = ['18A38', '853K83']
const dataOject =
[ { id:'853K83', isGo:false }
, { id:'18A38', isGo:true }
, { id:'97T223', isGo:true }
, { id:'18A38', isGo:false }
, { id:'182B92', isGo:true }
];
const result = dataOject.reduce((final, value, index) => {
if (checkArray.includes(value.id)) {
return [...final, index];
}
return final;
}, []);
console.log(result);
0赞
inorganik
11/15/2023
#3
你可以使用 Array.reduce() 来做到这一点
const checkArray = ['18A38']
const dataObject = [
{ id:'853K83', isGo:false },
{ id:'18A38', isGo:true },
{ id:'97T223', isGo:true },
{ id:'18A38', isGo:false },
{ id:'182B92', isGo:true },
];
const result = dataObject.reduce((acc, val, i) => {
if (checkArray.includes(val.id)) {
acc.push(i)
}
return acc;
}, [])
console.log( JSON.stringify(result))
1赞
itsvic
11/15/2023
#4
您可能希望先从 dataOject 数组开始。你有没有想过做一个findIndex? 这样你就可以支持你的checkArray。
checkArray = ['18A38',"18A38"]
dataObject =
[ { id:'853K83', isGo:false }
, { id:'18A38', isGo:true }
, { id:'97T223', isGo:true }
, { id:'18A38', isGo:false }
, { id:'182B92', isGo:true }
];
const filteredData = checkArray.map(input => dataObject.findIndex(el => el.id === input));
console.log(filteredData)
评论