使用nodejs在对象数组中查找特定键值

时间:2018-01-17 07:07:37

标签: javascript arrays json node.js lodash

我们有一个像

这样的JSON对象
var jsons = {
    "LAPTOP": [{
        "productId": "123"
    }],
    "DESKTOP": [{
        "productId": "456"
    }],
    "MOUSE": [{
        "productId": "789"
    }, {
        "productId": "012"
    }],
    "KEY-BOARD": [{
        "productId": "345"
    }]
}

如果我们搜索{ "productId": "012" }它应该返回密钥DESKTOP 如果我们可以使用lodash

那就太好了

7 个答案:

答案 0 :(得分:2)

试试这个



var jsons = {
"LAPTOP": [{
    "productId": "123"
}],
"DESKTOP": [{
    "productId": "456"
}],
"MOUSE": [{
    "productId": "789"
}, {
    "productId": "012"
}],
"KEY-BOARD": [{
    "productId": "345"
}]};

var result = Object.keys(jsons).find((key) => {
	   return jsons[key].find((item) => item.productId === '123')
    });

console.log(result);
    




答案 1 :(得分:2)

使用lodash的解决方案:

let result = _(jsons)
    .pickBy(item => _.some(item, {productId: '123'}))
    .keys()
    .head();

首先,我们找到值包含的键,并使用匹配的productId找到对象。然后我们从密钥集合中取出第一个密钥。

答案 2 :(得分:0)

没有LODASH你可以有这样的东西

var toSearch = 789;
Object.keys(jsons).forEach((key) => {
  if(jsons[key].find((pid) => pid.productId == toSearch)){
    console.log(key)
  }
})

答案 3 :(得分:0)

var jsons = {
"LAPTOP": [{
    "productId": "123"
}],
"DESKTOP": [{
    "productId": "456"
}],
"MOUSE": [{
    "productId": "789"
}, {
    "productId": "012"
}],
"KEY-BOARD": [{
    "productId": "345"
}]
};

var id = "789";
for(item in jsons){
  jsons[item].forEach(function(data){
    if(data.productId == id){
      console.log(item);
    }
  });
}

答案 4 :(得分:0)

您可以使用Javascript的key in object循环语法,如下所示:

var jsons = {
"LAPTOP": [{
    "productId": "123"
}],
"DESKTOP": [{
    "productId": "456"
}],
"MOUSE": [{
    "productId": "789"
}],
"KEY-BOARD": [{
    "productId": "345"
}]};

var searchFor = "789";

for(var key in jsons) 
  if(jsons.hasOwnProperty(key))
    if(jsons[key][0] && jsons[key][0].productId === searchFor)
      alert(key); // MOUSE

答案 5 :(得分:0)

您可以使用keysfind



var jsons = { "LAPTOP": [{ "productId": "123" }], "DESKTOP": [{ "productId": "456" }], "MOUSE": [{ "productId": "789" }, { "productId": "012" }], "KEY-BOARD": [{ "productId": "345" }] },
    value = { "productId": "012" };

var result = _.find(_.keys(jsons), key => _.find(jsons[key], value));
console.log(result);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
&#13;
&#13;
&#13;

答案 6 :(得分:0)

请考虑使用object-scan。将头包裹起来,它就非常强大

const objectScan = require('object-scan');

const search = (term, input) => {
  const r = objectScan(['**.productId'], {
    abort: true,
    rtn: 'key',
    filterFn: ({ value }) => value === term
  })(input);
  return r === undefined ? r : r[0];
};

const jsons = {
  LAPTOP: [{
    productId: '123'
  }],
  DESKTOP: [{
    productId: '456'
  }],
  MOUSE: [{
    productId: '789'
  }, {
    productId: '012'
  }],
  'KEY-BOARD': [{
    productId: '345'
  }]
};

console.log(search('012', jsons));
// => MOUSE