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

问题描述 投票:-1回答:1

我想定义一个函数来查找数组中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.
 });
}
javascript node.js json
1个回答
0
投票

.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));
© www.soinside.com 2019 - 2024. All rights reserved.