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

例如:

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

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


当前回答

您可以通过这种方式访问它

data.items[1].name

or

data["items"][1]["name"]

两边相等。

其他回答

// const path = 'info.value[0].item'
// const obj = { info: { value: [ { item: 'it works!' } ], randominfo: 3 }  }
// getValue(path, obj)

export const getValue = ( path , obj) => {
  const newPath = path.replace(/\]/g, "")
  const arrayPath = newPath.split(/[\[\.]+/) || newPath;

  const final = arrayPath.reduce( (obj, k) => obj ?  obj[k] : obj, obj)
  return final;
}

你需要做的非常简单,它可以通过递归来实现:

const json_object = {
        "item1":{
            "name": "apple",
            "value": 2,
        },
        "item2":{
            "name": "pear",
            "value": 4,
        },
        "item3":{
            "name": "mango",
            "value": 3,
            "prices": {
                "1": "9$",
                "2": "59$",
                "3": "1$"
            }
        }
    }
    
    function walkJson(json_object){
        for(obj in json_object){
            if(typeof json_object[obj] === 'string'){
                console.log(`${obj}=>${json_object[obj]}`);
            }else{
                console.log(`${obj}=>${json_object[obj]}`);
                walkJson(json_object[obj]);
            }
        }           
    }
    
    walkJson(json_object);

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>

您可以通过这种方式访问它

data.items[1].name

or

data["items"][1]["name"]

两边相等。

以防万一,有人在2017年或以后访问这个问题,并寻找一种容易记住的方法,这里有一篇关于在JavaScript中访问嵌套对象而不被迷惑的详细博客文章

无法读取未定义错误的属性“foo”

1. Oliver Steele的嵌套对象访问模式

最简单、最干净的方法是使用Oliver Steele的嵌套对象访问模式

const name = ((user || {}).personalInfo || {}).name;

用这个符号,你永远不会碰到

无法读取未定义的属性“名称”。

你基本上检查user是否存在,如果不存在,你立即创建一个空对象。这样,下一层键将始终从一个存在的对象或空对象访问,而不会从undefined访问。

2. 使用数组缩减访问嵌套对象

为了能够访问嵌套数组,您可以编写自己的数组reduce util。

const getNestedObject = (nestedObj, pathArr) => {
    return pathArr.reduce((obj, key) =>
        (obj && obj[key] !== 'undefined') ? obj[key] : undefined, nestedObj);
}

// pass in your object structure as array elements
const name = getNestedObject(user, ['personalInfo', 'name']);

// to access nested array, just pass in array index as an element the path array.
const city = getNestedObject(user, ['personalInfo', 'addresses', 0, 'city']);
// this will return the city from the first address item.

还有一种出色的类型处理最小库类型可以为您完成所有这些。