我想定义一个函数来查找数组中JSON对象的索引。 JSON对象是动态的。这里的对象键/属性在JSON中不是常数。
如何在数组中找到匹配对象的索引(所有键和值)?
例如:
let obj={name:'Bill', phone:'8562456871', email:'[email protected]'};
let arrayObj=[{street:'wardcircle', city:'Brentwood'},{name:'wan',email:'[email protected]' },{name:'bill', phone:'8562456871', email:'[email protected]'}];
let indx=getIndex(obj,arrayObj); // expected result is 2
我已经定义了这样的功能,但不适用于所有动态属性和值:
getIndex(obj,arrayObj){
Object.keys(obj),forEach((key,index)=>{
return arrayObject.findIndex(x=>x[key]==obj[key]);// Here I am unable to add AND condition for other key& values.
});
}
将.findIndex
first放入并在其中,检查.every
中的Object.keys
是否匹配。
[请注意,您当前的对象具有name: 'Bill'
,但数组具有name: 'bill'
-值应该匹配,区分大小写很重要(除非您要忽略它,在这种情况下,您必须在两个值上都调用toLowerCase()
首先)。
let obj = {
name: 'bill',
phone: '8562456871',
email: '[email protected]'
};
let arrayObj = [{
street: 'wardcircle',
city: 'Brentwood'
}, {
name: 'wan',
email: '[email protected]'
}, {
name: 'bill',
phone: '8562456871',
email: '[email protected]'
}];
const getIndex = (findObj, array) => (
array.findIndex(obj => (
Object.entries(findObj).every(([key, val]) => obj[key] === val)
))
);
console.log(getIndex(obj, arrayObj));
如果还要确保找到的对象没有findObj
中没有的任何属性,请检查两个对象上的键数是否也相同:
let obj = {
name: 'bill',
phone: '8562456871',
email: '[email protected]'
};
let arrayObj = [{
street: 'wardcircle',
city: 'Brentwood'
}, {
name: 'wan',
email: '[email protected]'
}, {
name: 'bill',
phone: '8562456871',
email: '[email protected]'
}];
const getIndex = (findObj, array) => (
array.findIndex(obj => (
Object.keys(obj).length === Object.keys(findObj).length &&
Object.entries(findObj).every(([key, val]) => obj[key] === val)
))
);
console.log(getIndex(obj, arrayObj));