简体   繁体   中英

Return JSON Object by Value of a Key

I have a huge nested JSON object, and need to find a specific one by a certain value of a certain key.

For example:

[ { 
      id: 't53',
      action: 'Boot',
      time: 2019-04-21T17:58:34.579Z
  },
  { 
      id: 't54',
      action: 'Reset',
      time: 2019-04-24T17:57:33.549Z
  } ]

So, if need to find the object where action is Boot , and the result must be:

{ 
    id: 't54',
    action: 'Boot',
    time: 2019-04-24T17:57:33.549Z
}

You can use the Array.find method to get the first item that matches the condition.

const item = objs.find(obj => obj.action === 'Boot');

If you want to find the first element from last, you could create a shallow copy of the array and reverse it.

const item = objs.slice().reverse().find(obj => obj.action === 'Boot');
var data = [{ 
      id: 't53',
      action: 'Boot',
      time: '2019-04-21T17:58:34.579Z'
  },
  { 
      id: 't54',
      action: 'Boot',
      time: '2019-04-24T17:57:33.549Z'
  }];


var result = data.filter(a => a.action === 'Boot');

console.log(result);

map, reducer, forEach and filter built-in functions are an efficient way of handling this situation.

In your case, you can use filter function like this:

yourArray.filter(item => item.action==='Boot)

您遍历数组并检查每个项目操作键是否需要。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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