[英]How to get index of a dynamic JSON object in an array using javascript
I want to define a function to find index of a JSON object in an array.我想定义一个 function 以在数组中查找 JSON object 的索引。 The JSON object is dynamic. JSON object 是动态的。 Here object keys/attributes are not constant in JSON .这里 object 键/属性在 JSON 中不是恒定的。
How to find index of matched object (all key& values) in array?如何在数组中找到匹配的 object(所有键和值)的索引?
For example:例如:
let obj={name:'Bill', phone:'8562456871', email:'bill@email.com'};
let arrayObj=[{street:'wardcircle', city:'Brentwood'},{name:'wan',email:'wan@test.com' },{name:'bill', phone:'8562456871', email:'bill@email.com'}];
let indx=getIndex(obj,arrayObj); // expected result is 2
I have defined function like this but it is not working for all dynamic attribute & values:我已经像这样定义了 function 但它不适用于所有动态属性和值:
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.
});
}
Put the .findIndex
first , and inside it, check that .every
one of the Object.keys
matches.将.findIndex
放在首位,然后在其中检查.every
中的每一个Object.keys
匹配。
Note that your current object has name: 'Bill'
but the array has name: 'bill'
- the values should match, case sensitivity matters (unless you want to ignore it, in which case you'll have to call toLowerCase()
on both values first).请注意,您当前的 object 的name: 'Bill'
但数组的name: 'bill'
- 值应该匹配,区分大小写很重要(除非您想忽略它,在这种情况下,您必须调用toLowerCase()
两个值都优先)。
let obj = { name: 'bill', phone: '8562456871', email: 'bill@email.com' }; let arrayObj = [{ street: 'wardcircle', city: 'Brentwood' }, { name: 'wan', email: 'wan@test.com' }, { name: 'bill', phone: '8562456871', email: 'bill@email.com' }]; const getIndex = (findObj, array) => ( array.findIndex(obj => ( Object.entries(findObj).every(([key, val]) => obj[key] === val) )) ); console.log(getIndex(obj, arrayObj));
If you also want to make sure that the found object doesn't have any properties not in the findObj
, check that the number of keys on both are the same too:如果您还想确保找到的 object 没有任何不在findObj
中的属性,请检查两者上的键数是否相同:
let obj = { name: 'bill', phone: '8562456871', email: 'bill@email.com' }; let arrayObj = [{ street: 'wardcircle', city: 'Brentwood' }, { name: 'wan', email: 'wan@test.com' }, { name: 'bill', phone: '8562456871', email: 'bill@email.com' }]; 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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.