Javascript / Lodash / Redux - 从对象返回具有特定id的对象

时间:2017-10-30 09:45:55

标签: javascript json reactjs redux lodash

所以我们说我们有一个对象:

names:
    {
     0: {"id": 30, name: "Adam"},
     1: {"id": 1, name: "Ben"},
     2: {"id": 15, name: "John"},
     ...
    }

并使用lodash get函数我想将特定名称保存为常量。

const name = _.get(state, ['names', nameId]);

我知道这不起作用,因为我选择了对象的密钥而不是id。知道怎么解决吗?请注意,我无法规范化数据,例如将id用作对象的键,因为它会破坏这些数据来自BE的顺序。是否可以遍历对象并查找特定的ID?

我正在从其他功能

获得nameId

3 个答案:

答案 0 :(得分:2)

不需要Lodash。只需遍历对象的属性,即可在id上找到匹配项:

const names = {
 0: {"id": 30, name: "Adam"},
 1: {"id": 1, name: "Ben"},
 2: {"id": 15, name: "John"}
};
const nameId = 1;
let obj;
for (const name in names) {
  if (names[name].id == nameId) {
    obj = names[name];
    break;
  }
}
console.log(obj);

或者使用Object.keyssome,但除了跳过继承的属性之外,它并没有真正购买任何东西:

const names = {
 0: {"id": 30, name: "Adam"},
 1: {"id": 1, name: "Ben"},
 2: {"id": 15, name: "John"}
};
const nameId = 1;
let obj;
Object.keys(names).some(name => {
  if (names[name].id == nameId) {
    obj = names[name];
    return true;
  }
});
console.log(obj);

或者使用ES2017的Object.values (可以轻松填充旧版环境)find

const names = {
 0: {"id": 30, name: "Adam"},
 1: {"id": 1, name: "Ben"},
 2: {"id": 15, name: "John"}
};
const nameId = 1;
const obj = Object.values(names).find(entry => entry.id == nameId);
console.log(obj);

答案 1 :(得分:0)

您可以_.find()_.values()一起使用 id 来获取特定对象。

var state = {names:{
  0: {"id": 30, name: "Adam"},
  1: {"id": 1, name: "Ben"},
  2: {"id": 15, name: "John"},
}}

var r = _.find(_.values(state.names), {id: 1})
console.log(r)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

答案 2 :(得分:0)

尝试这种简单的方法

_mm256_storeu_pd
  • 迭代对象值&#39;数组使用<!DOCTYPE html> <html> <head> <title>Bootstrap Tree View</title> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> <link href="./TreeView_files/bootstrap-treeview.css" rel="stylesheet"> </head> <body> <div class="container"> <h1>Bootstrap Tree View - DOM Tree</h1> <br/> <div class="row"> <div class="col-sm-12"> <label for="treeview"></label> <div id="treeview"/> </div> </div> </div> <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> <script src="./TreeView_files/bootstrap-treeview.js"></script> <script type="text/javascript"> function buildDomTree() { var tree = [ { text: "Parent 1", nodes: [ { text: "Child 1", nodes: [ { text: "Grandchild 1" }, { text: "Grandchild 2" } ] }, { text: "Child 2" } ] }, { text: "Parent 2" }, { text: "Parent 3" }, { text: "Parent 4" }, { text: "Parent 5" } ]; return tree; } $(function() { var options = { bootstrap2: false, showTags: true, levels: 5, data: buildDomTree() }; $('#treeview').treeview(options); }); </script> </body>

  • 通过var output = Object.values( obj.names ).find( function( item ){ return item.id = inputId }).name; 比较

  • ,使用Object.values获取具体价值
  • 获取返回对象的find属性。

<强>演示

&#13;
&#13;
id
&#13;
&#13;
&#13;