如何根據物件陣列的條件獲取所有索引?我試過下面的代碼,但它只回傳第一次出現。
a = [
{prop1:"abc",prop2:"yutu"},
{prop1:"bnmb",prop2:"yutu"},
{prop1:"zxvz",prop2:"qwrq"}];
index = a.findIndex(x => x.prop2 ==="yutu");
console.log(index);
uj5u.com熱心網友回復:
findIndex將只回傳一個匹配的索引,您可以prop2使用filter
a = [
{prop1:"abc",prop2:"yutu"},
{prop1:"bnmb",prop2:"yutu"},
{prop1:"zxvz",prop2:"qwrq"}];
const allIndexes = a
.map((e, i) => e.prop2 === 'yutu' ? i : -1)
.filter(index => index !== -1);
console.log(allIndexes);
// This is one liner solution might not work in older IE ('flatMap')
const notSupportedInIE =a.flatMap((e, i) => e.prop2 === 'yutu' ? i : []);
console.log(notSupportedInIE);
uj5u.com熱心網友回復:
嘗試 Array.reduce
a = [
{prop1:"abc",prop2:"yutu"},
{prop1:"bnmb",prop2:"yutu"},
{prop1:"zxvz",prop2:"qwrq"}];
index = a.reduce((acc, {prop2}, index) => prop2 ==="yutu" ? [...acc, index] : acc, []);
console.log(index);
uj5u.com熱心網友回復:
您可以使用普通的 for 回圈,并且當prop2匹配項推送陣列中的索引時
const a = [{
prop1: "abc",
prop2: "yutu"
},
{
prop1: "bnmb",
prop2: "yutu"
},
{
prop1: "zxvz",
prop2: "qwrq"
}
];
const indArr = [];
for (let i = 0; i < a.length; i ) {
if (a[i].prop2 === 'yutu') {
indArr.push(i)
}
}
console.log(indArr);
uj5u.com熱心網友回復:
該
findIndex方法回傳陣列中滿足提供的測驗函式的第一個元素的索引。否則回傳-1,表示沒有元素通過測驗。- MDN
你可以reduce在這里使用:
const a = [
{ prop1: "abc", prop2: "yutu" },
{ prop1: "bnmb", prop2: "yutu" },
{ prop1: "zxvz", prop2: "qwrq" },
];
const result = a.reduce((acc, curr, i) => {
if (curr.prop2 === "yutu") acc.push(i);
return acc;
}, []);
console.log(result);
uj5u.com熱心網友回復:
您可以簡單地遍歷物件,例如
function getIndexes(hystack, nameOfProperty, needle) {
const res = new Array();
for (const [i, item] of hystack.entries()) {
if (item[nameOfProperty] === needle) res.push(i);
}
return res;
}
const items =
[
{prop1:"a", prop2:"aa"},
{prop1:"b", prop2:"bb"},
{prop1:"c", prop2:"aa"},
{prop1:"c", prop2:"bb"},
{prop1:"d", prop2:"cc"}
];
const indexes = getIndexes(items, 'prop2', 'bb');
console.log('Result', indexes);
uj5u.com熱心網友回復:
filter不用map函式就可以直接使用
const a = [
{ prop1: "abc", prop2: "yutu" },
{ prop1: "bnmb", prop2: "yutu" },
{ prop1: "zxvz", prop2: "qwrq" },
];
const res = a.filter((item) => {
return item.prop2==="yutu";
});
console.log(res);
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/380344.html
標籤:javascript 数组 Vue.js
上一篇:如何使用v-for洗掉行
