如何使用javascript获取数组中动态JSON对象的索引

我想定义一个函数来查找数组中 JSON 对象的索引。JSON 对象是动态的。这里对象键/属性在 JSON 中不是常量。


如何在数组中找到匹配对象(所有键和值)的索引?


例如:


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

我已经定义了这样的函数,但它不适用于所有动态属性和值:


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.

 });

}


蝴蝶不菲
浏览 296回答 1
1回答

慕侠2389804

放入第.findIndex 一个,并在其中检查其中.every一个Object.keys匹配项。请注意,您当前的对象有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));如果您还想确保找到的对象没有任何不在 中的属性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));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript