简体   繁体   中英

get the object which property contains an array as the value using javascript

I have an array containing some objects like this :

var lists = [{
  "id": 1,
  "status": 1,
  "inputs": [],
  "outputs": [
    ""
  ]
}, {
  "id": "",
  "status": 1,
  "inputs": [
    "test",
    ""
  ],
  "outputs": [
    ""
  ]
}, {
  "id": "",
  "status": 1,
  "inputs": [
    "",
    "test1"
  ],
  "outputs": [
    ""
  ]
}, {
  "id": "",
  "status": 1,
  "inputs": [
    "gfg",
    ""
  ],
  "outputs": [
    ""
  ]
}];

From this array I want to get all objects in which the inputs property contains at least one element. How can I do this?

You almost had it:

function getObjects(lists) {
  return lists.filter(function (el) {
    return el.inputs.length;
  });
}

var arr = getObjects(lists);

DEMO

You just need to filter the array and return only items which has length of inputs array greater than zero . It can be achieved for example like this

var x=lists.filter(function(x){return x.inputs.length>=1});

Now x is the array that containts only objcets whose input array isnt empty.

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