我想知道如何根據 javascript 中的值匹配來獲取物件陣列串列
如果任何物件值與引數匹配,則在 javascript 中回傳該陣列。
var objarr = [
{id:1, email: '[email protected]', value: 10, name: 'ram'},
{id:2, email: '[email protected]', value: 20, name: 'Tom'},
{id:3, email: '[email protected]', value: 30, name: 'Lucas'},
{id:4, email: '[email protected]', value: 40, name: 'Chris'},
{id:5, email: '[email protected]', value: 30, name: 'Lucas Tim'}
]
function getList(val){
var result=[];
var checkdata = objarr.filter(e=>{
if(Object.values(e)===val){
result.push(e);
}
return result;
})
}
console.log(result);
Expected Output:
getList('[email protected]');
scenario 1:
[
{id:1, email: '[email protected]', value: 10, name: 'ram'},
{id:2, email: '[email protected]', value: 20, name: 'Tom'}
]
scenario 2:
getList('Chris');
[
{id:4, email: '[email protected]', value: 40, name: 'Chris'}
]
uj5u.com熱心網友回復:
您的Array.filter函式應根據搜索條件回傳true或false。
Object.values回傳一個陣列作為輸出。要檢查某個值是否在陣列中,您可以使用Array.includes.
你應該檢查價值 Object.values(e).includes(val)
作業小提琴
var objarr = [
{ id: 1, email: '[email protected]', value: 10, name: 'ram' },
{ id: 2, email: '[email protected]', value: 20, name: 'Tom' },
{ id: 3, email: '[email protected]', value: 30, name: 'Lucas' },
{ id: 4, email: '[email protected]', value: 40, name: 'Chris' },
{ id: 5, email: '[email protected]', value: 30, name: 'Lucas Tim' }
]
function getList(val) {
var checkdata = objarr.filter(e => {
if (Object.values(e).includes(val)) {
return true;
}
return false;
})
return checkdata;
}
console.log(getList('[email protected]'));
console.log(getList('Chris'));
簡化版
var objarr = [
{ id: 1, email: '[email protected]', value: 10, name: 'ram' },
{ id: 2, email: '[email protected]', value: 20, name: 'Tom' },
{ id: 3, email: '[email protected]', value: 30, name: 'Lucas' },
{ id: 4, email: '[email protected]', value: 40, name: 'Chris' },
{ id: 5, email: '[email protected]', value: 30, name: 'Lucas Tim' }
]
const getList = (val) => objarr.filter(e => Object.values(e).includes(val))
console.log(getList('[email protected]'));
console.log(getList('Chris'));
uj5u.com熱心網友回復:
您可以使用filterand usingObject.values來獲取物件的所有值,然后使用some來獲取所需的結果。
ONE LINER
objarr.filter((o) => Object.values(o).some((v) => v === val));
var objarr = [
{ id: 1, email: "[email protected]", value: 10, name: "ram" },
{ id: 2, email: "[email protected]", value: 20, name: "Tom" },
{ id: 3, email: "[email protected]", value: 30, name: "Lucas" },
{ id: 4, email: "[email protected]", value: 40, name: "Chris" },
{ id: 5, email: "[email protected]", value: 30, name: "Lucas Tim" },
];
const getList = val => objarr.filter((o) => Object.values(o).some(v => v === val));
console.log(getList("[email protected]"));
console.log(getList("Chris"));
/* This is not a part of answer. It is just to give the output full height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/365484.html
標籤:javascript 数组 循环 目的
