在嵌套数组对象中查找对象键

时间:2019-01-09 10:58:43

标签: javascript object indexof

我有一个对象,我会在{FIABILITE:XXX,RECTIVITE:YYY}中得到region=AAA(或其他)中的VOYAGES(我不需要在ICC中进行搜索)

这就是我试图获取数据的方式

const activityName = 'VOYAGES' // activityName: VOYAGES Or ICC
const  queryParams = [',','region=AAA']
const objectifs = {
  'VOYAGES': [
    {
      'region=AAA': {
        FIABILITE: '75',
        REACTIVITE: '90'
      }
    },
    {
      'region=BBBB': {
        FIABILITE: '75',
        REACTIVITE: '86'
      }
    }
  ],
  'ICC': [
    {
      'region=CSIC': {
        FIABILITE: '45',
        REACTIVITE: '80'
      }
    }
  ]
}


const objKeys = Object.values(objectifs[activityName])
const index = objKeys.indexOf((queryParams[1]));
const data = objectifs[activityName][index]; 
console.log(data)

实际上data是未定义的。

例如,我想获得{FIABILITE:XXX,RECTIVITE:YYY}中的region=AAA

3 个答案:

答案 0 :(得分:0)

由于未定义对象是如何创建对象的,因此需要添加索引objectifs['VOYAGES'][0]['region=AAA']

objectifs = {
  'VOYAGES': [{
      'region=AAA': {
        FIABILITE: '75',
        REACTIVITE: '90'
      }
    },
    {
      'region=BBBB': {
        FIABILITE: '75',
        REACTIVITE: '86'
      }
    }
  ],
  'ICC': [{
    'region=CSIC': {
      FIABILITE: '45',
      REACTIVITE: '80'
    }
  }]
}
var data = {}

objectifs['VOYAGES'].forEach(function(element) {
  if ('region=AAA' in element) {
    data = element['region=AAA'];
  }
});

console.log(data)

答案 1 :(得分:0)

您可以尝试:

const queryParams = [',','region=AAA']
const activityName = 'VOYAGES' 
const searchKey = queryParams[1];

objectif={'VOYAGES': [
    {
        'region=AAA': {
            FIABILITE: '75',
            REACTIVITE: '90'
        }
    },
    {
        'region=BBBB': {
            FIABILITE: '75',
            REACTIVITE: '86'
        }
    }
],
'ICC': [
    {
        'region=CSIC': {
            FIABILITE: '45',
            REACTIVITE: '80'
        }
    }
]};

let resultData = objectif[activityName].find((entry) => {
  return entry[searchKey];
})[searchKey];

console.log("Result data: ", resultData);

答案 2 :(得分:0)

您可以使用以下方法在具有特定属性的对象数组中找到index

const index = objectifs[activityName].findIndex(x => !!x[queryParams[1]])

工作示例:

const activityName = 'VOYAGES' // activityName: VOYAGES Or ICC
const  queryParams = [',','region=AAA']
const objectifs = {
  'VOYAGES': [
    {
      'region=AAA': {
        FIABILITE: '75',
        REACTIVITE: '90'
      }
    },
    {
      'region=BBBB': {
        FIABILITE: '75',
        REACTIVITE: '86'
      }
    }
  ],
  'ICC': [
    {
      'region=CSIC': {
        FIABILITE: '45',
        REACTIVITE: '80'
      }
    }
  ]
}

const index = objectifs[activityName].findIndex(x => x.hasOwnProperty([queryParams[1]]));

const data = objectifs[activityName][index]; 
console.log(data)

const obj = data[queryParams[1]];
console.log(obj)