我有一个包含对象和数组的嵌套数据结构。我如何提取信息,即访问一个特定的或多个值(或键)?

例如:

var data = {
    code: 42,
    items: [{
        id: 1,
        name: 'foo'
    }, {
        id: 2,
        name: 'bar'
    }]
};

我如何访问项目中的第二个项目的名称?


当前回答

jQuery的grep函数允许你过滤数组:

var data = { code: 42, items: [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }] }; $.grep(data.items, function(item) { if (item.id === 2) { console.log(item.id); //console id of item console.log(item.name); //console name of item console.log(item); //console item object return item; //returns item object } }); // Object {id: 2, name: "bar"} <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

其他回答

jQuery的grep函数允许你过滤数组:

var data = { code: 42, items: [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }] }; $.grep(data.items, function(item) { if (item.id === 2) { console.log(item.id); //console id of item console.log(item.name); //console name of item console.log(item); //console item object return item; //returns item object } }); // Object {id: 2, name: "bar"} <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

动态访问多级对象。

var obj = {
  name: "john doe",
  subobj: {
    subsubobj: {
      names: "I am sub sub obj"
    }
  }
};

var level = "subobj.subsubobj.names";
level = level.split(".");

var currentObjState = obj;

for (var i = 0; i < level.length; i++) {
  currentObjState = currentObjState[level[i]];
}

console.log(currentObjState);

工作提琴:https://jsfiddle.net/andreitodorut/3mws3kjL/

下面是一个使用对象扫描的答案。

当访问单个条目时,这个答案并没有提供比普通javascript更多的好处。然而,同时与多个字段交互,这个答案可以更有效。

下面是与单个字段交互的方法

// const objectScan = require('object-scan'); const data = { code: 42, items: [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }] }; const get = (haystack, needle) => objectScan([needle], { abort: true, rtn: 'value' })(haystack); const set = (haystack, needle, value) => objectScan([needle], { abort: true, rtn: 'bool', filterFn: ({ parent, property }) => { parent[property] = value; return true; } })(haystack); console.log(get(data, 'items[1].name')); // => bar console.log(set(data, 'items[1].name', 'foo2')); // => true console.log(data); // => { code: 42, items: [ { id: 1, name: 'foo' }, { id: 2, name: 'foo2' } ] } .as-console-wrapper {max-height: 100% !important; top: 0} <script src="https://bundle.run/object-scan@13.8.0"></script>

声明:我是object-scan的作者

下面是如何同时与多个字段交互

// const objectScan = require('object-scan'); const data = { code: 42, items: [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }] }; const get = (haystack, ...needles) => objectScan(needles, { joined: true, rtn: 'entry' })(haystack); const set = (haystack, actions) => objectScan(Object.keys(actions), { rtn: 'count', filterFn: ({ matchedBy, parent, property }) => { matchedBy.forEach((m) => { parent[property] = actions[m]; }) return true; } })(haystack); console.log(get(data, 'items[0].name', 'items[1].name')); // => [ [ 'items[1].name', 'bar' ], [ 'items[0].name', 'foo' ] ] console.log(set(data, { 'items[0].name': 'foo1', 'items[1].name': 'foo2' })); // => 2 console.log(data); // => { code: 42, items: [ { id: 1, name: 'foo1' }, { id: 2, name: 'foo2' } ] } .as-console-wrapper {max-height: 100% !important; top: 0} <script src="https://bundle.run/object-scan@13.8.0"></script>

声明:我是object-scan的作者


下面是如何在一个深度嵌套的对象中通过id搜索找到一个实体(正如在评论中问到的那样)

// const objectScan = require('object-scan'); const myData = { code: 42, items: [{ id: 1, name: 'aaa', items: [{ id: 3, name: 'ccc' }, { id: 4, name: 'ddd' }] }, { id: 2, name: 'bbb', items: [{ id: 5, name: 'eee' }, { id: 6, name: 'fff' }] }] }; const findItemById = (haystack, id) => objectScan(['**(^items$).id'], { abort: true, useArraySelector: false, rtn: 'parent', filterFn: ({ value }) => value === id })(haystack); console.log(findItemById(myData, 5)); // => { id: 5, name: 'eee' } .as-console-wrapper {max-height: 100% !important; top: 0} <script src="https://bundle.run/object-scan@13.8.0"></script>

声明:我是object-scan的作者

在2020年,你可以使用@babel/plugin-proposal-optional- chains,它很容易访问对象中的嵌套值。

 const obj = {
 foo: {
   bar: {
     baz: class {
   },
  },
 },
};

const baz = new obj?.foo?.bar?.baz(); // baz instance

const safe = new obj?.qux?.baz(); // undefined
const safe2 = new obj?.foo.bar.qux?.(); // undefined

https://babeljs.io/docs/en/babel-plugin-proposal-optional-chaining

https://github.com/tc39/proposal-optional-chaining

有时,使用字符串访问嵌套对象是可取的。例如,最简单的方法是第一级

var obj = { hello: "world" };
var key = "hello";
alert(obj[key]);//world

但复杂的json通常不是这样。随着json变得越来越复杂,在json中查找值的方法也变得越来越复杂。导航json的递归方法是最好的,如何利用递归取决于要搜索的数据类型。如果涉及到条件语句,json搜索可能是一个很好的工具。

如果已经知道要访问的属性,但是路径很复杂,例如在这个对象中

var obj = {
 arr: [
    { id: 1, name: "larry" },    
    { id: 2, name: "curly" },
    { id: 3, name: "moe" }
 ]
};

你知道你想要得到对象中数组的第一个结果,也许你想使用

var moe = obj["arr[0].name"];

然而,这将导致一个异常,因为对象没有该名称的属性。能够使用这种方法的解决方案是将对象的树形面平直。这可以递归完成。

function flatten(obj){
 var root = {};
 (function tree(obj, index){
   var suffix = toString.call(obj) == "[object Array]" ? "]" : "";
   for(var key in obj){
    if(!obj.hasOwnProperty(key))continue;
    root[index+key+suffix] = obj[key];
    if( toString.call(obj[key]) == "[object Array]" )tree(obj[key],index+key+suffix+"[");
    if( toString.call(obj[key]) == "[object Object]" )tree(obj[key],index+key+suffix+".");   
   }
 })(obj,"");
 return root;
}

现在,这个复杂的物体可以被平面化

var obj = previous definition;
var flat = flatten(obj);
var moe = flat["arr[0].name"];//moe

下面是使用这种方法的jsFiddle演示。