简体   繁体   English

在js中某个对象的键值对中找到特定值

[英]find a specific value in key-value pair of some object in js

i have been trying to match a certain value from the values(which is in array) of key-value pair.Like if i wanna search for id 462 ,i want to search it iteratively like first search in 2013 if not found then 2014 and so on. 我一直在尝试从键值对的值(数组中)中匹配某个值。如果我想搜索id 462,我想像在2013年第一次搜索时一样进行迭代搜索(如果找不到),然后在2014年和以此类推。

i have tried Object.values(x) but its returning all the arrays for both 2 years. 我已经尝试过Object.values(x),但是它返回了所有两年的所有数组。

x={'2013': 
   { matchId: 
      [ 
        '386',
        '387',
        '388',
        '389',
        '390',
         ] },
  '2014': 
   { matchId: 
      [
        '462',
        '463',
        '464',
        '465',
        '466',
         ] },

}

if value is found i want to insert some new key-value pair in that (year eg:-2013) like 如果找到值,我想在该年份(例如:-2013)中插入一些新的键值对,例如

{'2013': 
   { matchId: 
      [ 
        '386',
        '387',
        '388',
        '389',
        '390',
         ] 
      'Andrew':'23',
      'Castle':32}
}

Sort the keys, loop through them in order, and check if the value you want is in the array: 排序键,按顺序循环,然后检查所需的值是否在数组中:

const keys = Object.keys(x).sort();
const testValue = '462';
let foundKey;
for (let i = 0; i < keys.length; ++i) {
  if (x[keys[i]].matchId.includes(testValue)) {
    foundKey = keys[i];
    break;
  }
}

At the end of this, foundKey will be undefined if there's no match, or the key (year) of the first matching object if found. 最后,如果没有匹配项,则findKey将是未定义的,如果找到第一个匹配对象的键(年),则将是未定义的。

Iterate over the outer keys, years, and if the inner matchId array includes the search id, add it to the year object. 遍历外键,年份,如果内部matchId数组包含搜索ID,则将其添加到year对象。

 const data = { '2013': { matchId: ['386', '387', '388', '389', '390'] }, '2014': { matchId: ['462', '463', '464', '465', '466'] }, }; const addDataById = (array, searchId, data) => { return array && Object.values(array) .map(year => { if (year.matchId && Object.values(year.matchId).includes(searchId)) { return {...year, ...data}; } return year; }); }; const newData = addDataById(data, '462', { key: 'newData' }); console.log(newData); const newData2 = addDataById(data, '123', { key2: 'newData' }); console.log(newData2); console.log(addDataById(undefined, '462', { key: 'newData' })); console.log(addDataById(5, '462', { key: 'newData' })); console.log(addDataById('array', '462', { key: 'newData' })); 

you can use hasOwnProperty() method. 您可以使用hasOwnProperty()方法。 Use the below code to do your task 使用以下代码完成任务

 x = { '2013': { matchId: [ '386', '387', '388', '389', '390', ] }, '2014': { matchId: [ '462', '463', '464', '465', '466', ] }, } function findById(id) { for (var key in x) { if (x.hasOwnProperty(key)) { if (x[key]['matchId'].find(x => x == id)) { return { [key]: x[key] } } } } } console.log(findById('390')) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM