Javascript 如何访问和处理嵌套对象、数组或 JSON?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11922383/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I access and process nested objects, arrays or JSON?
提问by Felix Kling
I have a nested data structure containing objects and arrays. How can I extract the information, i.e. access a specific or multiple values (or keys)?
我有一个包含对象和数组的嵌套数据结构。如何提取信息,即访问特定或多个值(或键)?
For example:
例如:
var data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
How could I access the name
of the second item in items
?
我怎样才能访问name
中的第二项items
?
回答by Felix Kling
Preliminaries
预赛
JavaScript has only one data type which can contain multiple values: Object. An Arrayis a special form of object.
JavaScript 只有一种可以包含多个值的数据类型:Object。一个阵列是对象的一种特殊形式。
(Plain) Objects have the form
(普通)对象具有形式
{key: value, key: value, ...}
Arrays have the form
数组具有以下形式
[value, value, ...]
Both arrays and objects expose a key -> value
structure. Keys in an array must be numeric, whereas any string can be used as key in objects. The key-value pairs are also called the "properties".
数组和对象都公开一个key -> value
结构。数组中的键必须是数字,而任何字符串都可以用作对象中的键。键值对也称为“属性”。
Properties can be accessed either using dot notation
可以使用点符号访问属性
const value = obj.someProperty;
or bracket notation, if the property name would not be a valid JavaScript identifier name [spec], or the name is the value of a variable:
或括号表示法,如果属性名称不是有效的 JavaScript标识符名称[spec],或者名称是变量的值:
// the space is not a valid character in identifier names
const value = obj["some Property"];
// property name as variable
const name = "some Property";
const value = obj[name];
For that reason, array elements can only be accessed using bracket notation:
因此,只能使用括号表示法访问数组元素:
const value = arr[5]; // arr.5 would be a syntax error
// property name / index as variable
const x = 5;
const value = arr[x];
Wait... what about JSON?
等等... JSON 呢?
JSON is a textual representation of data, just like XML, YAML, CSV, and others. To work with such data, it first has to be converted to JavaScript data types, i.e. arrays and objects (and how to work with those was just explained). How to parse JSON is explained in the question Parse JSON in JavaScript?.
JSON 是数据的文本表示,就像 XML、YAML、CSV 等一样。要处理此类数据,首先必须将其转换为 JavaScript 数据类型,即数组和对象(以及如何处理这些已在刚刚解释过)。在 JavaScript 中解析 JSON的问题中解释了如何解析 JSON ?.
Further reading material
进一步阅读材料
How to access arrays and objects is fundamental JavaScript knowledge and therefore it is advisable to read the MDN JavaScript Guide, especially the sections
如何访问数组和对象是基本的 JavaScript 知识,因此建议阅读MDN JavaScript 指南,尤其是部分
Accessing nested data structures
访问嵌套数据结构
A nested data structure is an array or object which refers to other arrays or objects, i.e. its values are arrays or objects. Such structures can be accessed by consecutively applying dot or bracket notation.
嵌套数据结构是一个数组或对象,它引用其他数组或对象,即它的值是数组或对象。可以通过连续应用点或括号表示法来访问此类结构。
Here is an example:
下面是一个例子:
const data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
Let's assume we want to access the name
of the second item.
假设我们要访问name
第二项的 。
Here is how we can do it step-by-step:
以下是我们如何逐步做到这一点:
As we can see data
is an object, hence we can access its properties using dot notation. The items
property is accessed as follows:
正如我们所见,data
是一个对象,因此我们可以使用点表示法访问它的属性。该items
属性的访问方式如下:
data.items
The value is an array, to access its second element, we have to use bracket notation:
该值是一个数组,要访问它的第二个元素,我们必须使用括号表示法:
data.items[1]
This value is an object and we use dot notation again to access the name
property. So we eventually get:
该值是一个对象,我们再次使用点表示法来访问该name
属性。所以我们最终得到:
const item_name = data.items[1].name;
Alternatively, we could have used bracket notation for any of the properties, especially if the name contained characters that would have made it invalid for dot notation usage:
或者,我们可以对任何属性使用括号表示法,特别是如果名称包含会使点表示法使用无效的字符:
const item_name = data['items'][1]['name'];
I'm trying to access a property but I get only undefined
back?
我试图访问一个属性,但我只能undefined
回来?
Most of the time when you are getting undefined
, the object/array simply doesn't have a property with that name.
大多数情况下,当您获取 时undefined
,对象/数组根本没有具有该名称的属性。
const foo = {bar: {baz: 42}};
console.log(foo.baz); // undefined
Use console.log
or console.dir
and inspect the structure of object / array. The property you are trying to access might be actually defined on a nested object / array.
使用console.log
或console.dir
检查对象/数组的结构。您尝试访问的属性实际上可能是在嵌套对象/数组上定义的。
console.log(foo.bar.baz); // 42
What if the property names are dynamic and I don't know them beforehand?
如果属性名称是动态的而我事先不知道怎么办?
If the property names are unknown or we want to access all properties of an object / elements of an array, we can use the for...in
[MDN]loop for objects and the for
[MDN]loop for arrays to iterate over all properties / elements.
如果属性名称未知或我们要访问的对象的所有属性/数组元素,我们可以使用for...in
[MDN]环为目的和for
[MDN]环用于在所有属性/元素阵列进行迭代。
Objects
对象
To iterate over all properties of data
, we can iterate over the objectlike so:
要迭代 的所有属性data
,我们可以像这样迭代对象:
for (const prop in data) {
// `prop` contains the name of each property, i.e. `'code'` or `'items'`
// consequently, `data[prop]` refers to the value of each property, i.e.
// either `42` or the array
}
Depending on where the object comes from (and what you want to do), you might have to test in each iteration whether the property is really a property of the object, or it is an inherited property. You can do this with Object#hasOwnProperty
[MDN].
根据对象的来源(以及您想要做什么),您可能必须在每次迭代中测试该属性是否真的是对象的属性,还是继承的属性。你可以用Object#hasOwnProperty
[MDN]来做到这一点。
As alternative to for...in
with hasOwnProperty
, you can use Object.keys
[MDN]to get an array of property names:
作为for...in
with 的替代方法hasOwnProperty
,您可以使用Object.keys
[MDN]来获取属性名称数组:
Object.keys(data).forEach(function(prop) {
// `prop` is the property name
// `data[prop]` is the property value
});
Arrays
数组
To iterate over all elements of the data.items
array, we use a for
loop:
为了迭代data.items
数组的所有元素,我们使用一个for
循环:
for(let i = 0, l = data.items.length; i < l; i++) {
// `i` will take on the values `0`, `1`, `2`,..., i.e. in each iteration
// we can access the next element in the array with `data.items[i]`, example:
//
// var obj = data.items[i];
//
// Since each element is an object (in our example),
// we can now access the objects properties with `obj.id` and `obj.name`.
// We could also use `data.items[i].id`.
}
One could also use for...in
to iterate over arrays, but there are reasons why this should be avoided: Why is 'for(var item in list)' with arrays considered bad practice in JavaScript?.
也可以使用for...in
迭代数组,但有一些原因应该避免这样做:为什么在 JavaScript 中使用数组的 'for(var item in list)' 被认为是不好的做法?.
With the increasing browser support of ECMAScript 5, the array method forEach
[MDN]becomes an interesting alternative as well:
随着浏览器对 ECMAScript 5 支持的增加,数组方法forEach
[MDN] 也成为一个有趣的替代方案:
data.items.forEach(function(value, index, array) {
// The callback is executed for each element in the array.
// `value` is the element itself (equivalent to `array[index]`)
// `index` will be the index of the element in the array
// `array` is a reference to the array itself (i.e. `data.items` in this case)
});
In environments supporting ES2015 (ES6), you can also use the for...of
[MDN]loop, which not only works for arrays, but for any iterable:
在支持 ES2015 (ES6) 的环境中,您还可以使用[MDN]循环,它不仅适用于数组,还适用于任何可迭代的:for...of
for (const item of data.items) {
// `item` is the array element, **not** the index
}
In each iteration, for...of
directly gives us the next element of the iterable, there is no "index" to access or use.
在每次迭代中,for...of
直接给我们迭代的下一个元素,没有“索引”可以访问或使用。
What if the "depth" of the data structure is unknown to me?
如果我不知道数据结构的“深度”怎么办?
In addition to unknown keys, the "depth" of the data structure (i.e. how many nested objects) it has, might be unknown as well. How to access deeply nested properties usually depends on the exact data structure.
除了未知的键之外,数据结构的“深度”(即有多少嵌套对象)也可能是未知的。如何访问深度嵌套的属性通常取决于确切的数据结构。
But if the data structure contains repeating patterns, e.g. the representation of a binary tree, the solution typically includes to recursively[Wikipedia]access each level of the data structure.
但是如果数据结构包含重复模式,例如二叉树的表示,解决方案通常包括递归[维基百科]访问数据结构的每个级别。
Here is an example to get the first leaf node of a binary tree:
这是获取二叉树的第一个叶节点的示例:
function getLeaf(node) {
if (node.leftChild) {
return getLeaf(node.leftChild); // <- recursive call
}
else if (node.rightChild) {
return getLeaf(node.rightChild); // <- recursive call
}
else { // node must be a leaf node
return node;
}
}
const first_leaf = getLeaf(root);
const root = {
leftChild: {
leftChild: {
leftChild: null,
rightChild: null,
data: 42
},
rightChild: {
leftChild: null,
rightChild: null,
data: 5
}
},
rightChild: {
leftChild: {
leftChild: null,
rightChild: null,
data: 6
},
rightChild: {
leftChild: null,
rightChild: null,
data: 7
}
}
};
function getLeaf(node) {
if (node.leftChild) {
return getLeaf(node.leftChild);
} else if (node.rightChild) {
return getLeaf(node.rightChild);
} else { // node must be a leaf node
return node;
}
}
console.log(getLeaf(root).data);
A more generic way to access a nested data structure with unknown keys and depth is to test the type of the value and act accordingly.
访问具有未知键和深度的嵌套数据结构的更通用方法是测试值的类型并相应地采取行动。
Here is an example which adds all primitive values inside a nested data structure into an array (assuming it does not contain any functions). If we encounter an object (or array) we simply call toArray
again on that value (recursive call).
这是一个示例,它将嵌套数据结构中的所有原始值添加到数组中(假设它不包含任何函数)。如果我们遇到一个对象(或数组),我们只需toArray
再次调用该值(递归调用)。
function toArray(obj) {
const result = [];
for (const prop in obj) {
const value = obj[prop];
if (typeof value === 'object') {
result.push(toArray(value)); // <- recursive call
}
else {
result.push(value);
}
}
return result;
}
const data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
function toArray(obj) {
const result = [];
for (const prop in obj) {
const value = obj[prop];
if (typeof value === 'object') {
result.push(toArray(value));
} else {
result.push(value);
}
}
return result;
}
console.log(toArray(data));
Helpers
帮手
Since the structure of a complex object or array is not necessarily obvious, we can inspect the value at each step to decide how to move further. console.log
[MDN]and console.dir
[MDN]help us doing this. For example (output of the Chrome console):
由于复杂对象或数组的结构不一定很明显,我们可以检查每一步的值来决定如何进一步移动。console.log
[MDN]和console.dir
[MDN]帮助我们做到这一点。例如(Chrome 控制台的输出):
> console.log(data.items)
[ Object, Object ]
Here we see that that data.items
is an array with two elements which are both objects. In Chrome console the objects can even be expanded and inspected immediately.
在这里我们看到这data.items
是一个包含两个元素的数组,这两个元素都是对象。在 Chrome 控制台中,甚至可以立即展开和检查对象。
> console.log(data.items[1])
Object
id: 2
name: "bar"
__proto__: Object
This tells us that data.items[1]
is an object, and after expanding it we see that it has three properties, id
, name
and __proto__
. The latter is an internal property used for the prototype chain of the object. The prototype chain and inheritance is out of scope for this answer, though.
这告诉我们这data.items[1]
是一个对象,在展开它之后我们看到它具有三个属性id
,name
和__proto__
。后者是用于对象原型链的内部属性。但是,原型链和继承超出了这个答案的范围。
回答by vitmalina
You can access it this way
您可以通过这种方式访问它
data.items[1].name
or
或者
data["items"][1]["name"]
Both ways are equal.
两种方式都是平等的。
回答by holographic-principle
In case you're trying to access an item
from the example structure by id
or name
, without knowing it's position in the array, the easiest way to do it would be to use underscore.jslibrary:
如果您尝试item
通过id
or从示例结构访问 an name
,而不知道它在数组中的位置,最简单的方法是使用underscore.js库:
var data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
_.find(data.items, function(item) {
return item.id === 2;
});
// Object {id: 2, name: "bar"}
From my experience, using higher order functions instead of for
or for..in
loops results in code that is easier to reason about, and hence more maintainable.
从我的经验,使用高阶函数代替for
或for..in
循环使代码更容易的原因有关,因此更易于维护的结果。
Just my 2 cents.
只有我的 2 美分。
回答by Micha? Per?akowski
Objects and arrays has a lot of built-in methods that can help you with processing data.
对象和数组有很多内置方法可以帮助您处理数据。
Note: in many of the examples I'm using arrow functions. They are similar to function expressions, but they bind the this
value lexically.
注意:在许多示例中,我使用了箭头函数。它们类似于函数表达式,但它们在this
词法上绑定了值。
Object.keys()
, Object.values()
(ES 2017) and Object.entries()
(ES 2017)
Object.keys()
, Object.values()
(ES 2017) 和Object.entries()
(ES 2017)
Object.keys()
returns an array of object's keys, Object.values()
returns an array of object's values, and Object.entries()
returns an array of object's keys and corresponding values in a format [key, value]
.
Object.keys()
返回对象键Object.values()
的数组,返回对象值Object.entries()
的数组,并以格式返回对象的键和相应值的数组[key, value]
。
const obj = {
a: 1
,b: 2
,c: 3
}
console.log(Object.keys(obj)) // ['a', 'b', 'c']
console.log(Object.values(obj)) // [1, 2, 3]
console.log(Object.entries(obj)) // [['a', 1], ['b', 2], ['c', 3]]
Object.entries()
with a for-of loop and destructuring assignment
Object.entries()
使用 for-of 循环和解构赋值
const obj = {
a: 1
,b: 2
,c: 3
}
for (const [key, value] of Object.entries(obj)) {
console.log(`key: ${key}, value: ${value}`)
}
It's very convenient to iterate the result of Object.entries()
with a for-of loopand destructuring assignment.
Object.entries()
用for-of 循环和解构赋值来迭代结果非常方便。
For-of loop lets you iterate array elements. The syntax is for (const element of array)
(we can replace const
with var
or let
, but it's better to use const
if we don't intend to modify element
).
For-of 循环可让您迭代数组元素。语法是for (const element of array)
(我们可以const
用var
或替换let
,但const
如果我们不打算修改 ,最好使用element
)。
Destructuring assignment lets you extract values from an array or an object and assign them to variables. In this case const [key, value]
means that instead of assigning the [key, value]
array to element
, we assign the first element of that array to key
and the second element to value
. It is equivalent to this:
解构赋值允许您从数组或对象中提取值并将它们分配给变量。在这种情况下,const [key, value]
意味着不是将[key, value]
数组分配给 ,而是将该数组element
的第一个元素分配给key
,将第二个元素分配给value
。它相当于:
for (const element of Object.entries(obj)) {
const key = element[0]
,value = element[1]
}
As you can see, destructuring makes this a lot simpler.
如您所见,解构使这变得更加简单。
Array.prototype.every()
and Array.prototype.some()
Array.prototype.every()
和 Array.prototype.some()
The every()
method returns true
if the specified callback function returns true
for everyelement of the array. The some()
method returns true
if the specified callback function returns true
for some(at least one) element.
如果指定的回调函数为数组的每个元素every()
返回,true
则该方法返回。如果指定的回调函数为某个(至少一个)元素返回,则该方法返回。true
some()
true
true
const arr = [1, 2, 3]
// true, because every element is greater than 0
console.log(arr.every(x => x > 0))
// false, because 3^2 is greater than 5
console.log(arr.every(x => Math.pow(x, 2) < 5))
// true, because 2 is even (the remainder from dividing by 2 is 0)
console.log(arr.some(x => x % 2 === 0))
// false, because none of the elements is equal to 5
console.log(arr.some(x => x === 5))
Array.prototype.find()
and Array.prototype.filter()
Array.prototype.find()
和 Array.prototype.filter()
The find()
methods returns the firstelement which satisfies the provided callback function. The filter()
method returns an array of allelements which satisfies the provided callback function.
这些find()
方法返回满足提供的回调函数的第一个元素。该filter()
方法返回满足提供的回调函数的所有元素的数组。
const arr = [1, 2, 3]
// 2, because 2^2 !== 2
console.log(arr.find(x => x !== Math.pow(x, 2)))
// 1, because it's the first element
console.log(arr.find(x => true))
// undefined, because none of the elements equals 7
console.log(arr.find(x => x === 7))
// [2, 3], because these elements are greater than 1
console.log(arr.filter(x => x > 1))
// [1, 2, 3], because the function returns true for all elements
console.log(arr.filter(x => true))
// [], because none of the elements equals neither 6 nor 7
console.log(arr.filter(x => x === 6 || x === 7))
Array.prototype.map()
Array.prototype.map()
The map()
method returns an array with the results of calling a provided callback function on the array elements.
该map()
方法返回一个数组,其中包含对数组元素调用提供的回调函数的结果。
const arr = [1, 2, 3]
console.log(arr.map(x => x + 1)) // [2, 3, 4]
console.log(arr.map(x => String.fromCharCode(96 + x))) // ['a', 'b', 'c']
console.log(arr.map(x => x)) // [1, 2, 3] (no-op)
console.log(arr.map(x => Math.pow(x, 2))) // [1, 4, 9]
console.log(arr.map(String)) // ['1', '2', '3']
Array.prototype.reduce()
Array.prototype.reduce()
The reduce()
method reduces an array to a single value by calling the provided callback function with two elements.
该reduce()
方法通过调用提供的具有两个元素的回调函数将数组缩减为单个值。
const arr = [1, 2, 3]
// Sum of array elements.
console.log(arr.reduce((a, b) => a + b)) // 6
// The largest number in the array.
console.log(arr.reduce((a, b) => a > b ? a : b)) // 3
The reduce()
method takes an optional second parameter, which is the initial value. This is useful when the array on which you call reduce()
can has zero or one elements. For example, if we wanted to create a function sum()
which takes an array as an argument and returns the sum of all elements, we could write it like that:
该reduce()
方法采用可选的第二个参数,即初始值。当您调用的数组reduce()
可以有零个或一个元素时,这很有用。例如,如果我们想创建一个函数sum()
,它接受一个数组作为参数并返回所有元素的总和,我们可以这样写:
const sum = arr => arr.reduce((a, b) => a + b, 0)
console.log(sum([])) // 0
console.log(sum([4])) // 4
console.log(sum([2, 5])) // 7
回答by Travis J
At times, accessing a nested object using a string can be desirable. The simple approach is the first level, for example
有时,可能需要使用字符串访问嵌套对象。简单的方法是第一级,例如
var obj = { hello: "world" };
var key = "hello";
alert(obj[key]);//world
But this is often not the case with complex json. As json becomes more complex, the approaches for finding values inside of the json also become complex. A recursive approach for navigating the json is best, and how that recursion is leveraged will depend on the type of data being searched for. If there are conditional statements involved, a json searchcan be a good tool to use.
但是对于复杂的 json,情况通常不是这样。随着 json 变得越来越复杂,在 json 中查找值的方法也变得复杂。导航 json 的递归方法是最好的,并且如何利用递归将取决于正在搜索的数据类型。如果涉及条件语句,json 搜索可能是一个很好的工具。
If the property being accessed is already known, but the path is complex, for example in this object
如果正在访问的属性已知,但路径很复杂,例如在此对象中
var obj = {
arr: [
{ id: 1, name: "larry" },
{ id: 2, name: "curly" },
{ id: 3, name: "moe" }
]
};
And you know you want to get the first result of the array in the object, perhaps you would like to use
并且你知道你想得到对象中数组的第一个结果,也许你想使用
var moe = obj["arr[0].name"];
However, that will cause an exception as there is no property of object with that name. The solution to be able to use this would be to flatten the tree aspect of the object. This can be done recursively.
但是,这将导致异常,因为没有具有该名称的对象的属性。能够使用它的解决方案是展平对象的树方面。这可以递归完成。
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;
}
Now, the complex object can be flattened
现在,可以将复杂对象展平
var obj = previous definition;
var flat = flatten(obj);
var moe = flat["arr[0].name"];//moe
Here is a jsFiddle Demo
of this approach being used.
这是jsFiddle Demo
正在使用的这种方法。
回答by Alex KeySmith
This question is quite old, so as a contemporary update. With the onset of ES2015 there are alternatives to get a hold of the data you require. There is now a feature called object destructuringfor accessing nested objects.
这个问题很老了,所以作为当代更新。随着 ES2015 的出现,有其他方法可以获取您需要的数据。现在有一个称为对象解构的功能,用于访问嵌套对象。
const data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
const {
items: [, {
name: secondName
}]
} = data;
console.log(secondName);
The above example creates a variable called secondName
from the name
key from an array called items
, the lonely ,
says skip the first object in the array.
上面的例子创建了一个secondName
从名为name
的数组中的键调用的变量items
,孤独的,
说跳过数组中的第一个对象。
Notably it's probably overkill for this example, as simple array acccess is easier to read, but it comes in useful when breaking apart objects in general.
值得注意的是,对于这个例子来说,它可能有点矫枉过正,因为简单的数组访问更容易阅读,但它在分解一般对象时很有用。
This is very brief intro to your specific use case, destructuring can be an unusual syntax to get used to at first. I'd recommend reading Mozilla's Destructuring Assignment documentationto learn more.
这是对您的特定用例的非常简短的介绍,解构最初可能是一种不寻常的语法。我建议阅读Mozilla 的 Destructuring Assignment 文档以了解更多信息。
回答by Evgeny
To access a nested attribute, you need to specify its name and then search through the object.
要访问嵌套属性,您需要指定其名称,然后搜索对象。
If you already know the exact path, then you can hardcode it in your script like so:
如果您已经知道确切的路径,那么您可以像这样在脚本中对其进行硬编码:
data['items'][1]['name']
these also work -
这些也有效 -
data.items[1].name
data['items'][1].name
data.items[1]['name']
When you don't know the exact name before hand, or a user is the one who provides the name for you. Then dynamically searching through the data structure is required. Some suggested here that the search can be done using a for
loop, but there is a very simple way to traverse a path using Array.reduce
.
当您事先不知道确切名称时,或者是用户为您提供名称时。然后需要动态搜索数据结构。这里有人建议可以使用for
循环来完成搜索,但有一种非常简单的方法可以使用Array.reduce
.
const data = { code: 42, items: [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }] }
const path = [ 'items', '1', 'name']
let result = path.reduce((a,v) => a[v], data)
The path is a way to say: First take the object with key items
, which happens to be an array. Then take the 1
-st element (0 index arrays). Last take the object with key name
in that array element, which happens to be the string bar
.
路径是这样说的:首先获取带有 key 的对象items
,它恰好是一个数组。然后取1
-st 元素(0 索引数组)。最后获取该name
数组元素中带有键的对象,恰好是 string bar
。
If you have a very long path, you might even use String.split
to make all of this easier -
如果你有很长的路,你甚至可以String.split
用来让这一切变得更容易——
'items.1.name'.split('.').reduce((a,v) => a[v], data)
This is just plain JavaScript, without using any third party libraries like jQuery or lodash.
这只是简单的 JavaScript,没有使用任何第三方库,如 jQuery 或 lodash。
回答by Johnny
var ourStorage = {
"desk": {
"drawer": "stapler"
},
"cabinet": {
"top drawer": {
"folder1": "a file",
"folder2": "secrets"
},
"bottom drawer": "soda"
}
};
ourStorage.cabinet["top drawer"].folder2; // Outputs -> "secrets"
or
或者
//parent.subParent.subsubParent["almost there"]["final property"]
Basically, use a dot between each descendant that unfolds underneath it and when you have object names made out of two strings, you must use the ["obj Name"] notation. Otherwise, just a dot would suffice;
基本上,在它下面展开的每个后代之间使用一个点,当您的对象名称由两个字符串组成时,您必须使用 ["obj Name"] 表示法。否则,只需一个点就足够了;
来源:https: //learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/accessing-nested-objects
to add to this, accessing nested Arrays would happen like so:
除此之外,访问嵌套数组会像这样发生:
var ourPets = [
{
animalType: "cat",
names: [
"Meowzer",
"Fluffy",
"Kit-Cat"
]
},
{
animalType: "dog",
names: [
"Spot",
"Bowser",
"Frankie"
]
}
];
ourPets[0].names[1]; // Outputs "Fluffy"
ourPets[1].names[0]; // Outputs "Spot"
来源:https: //learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/accessing-nested-arrays/
Another more useful document depicting the situation above: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Basics#Bracket_notation
描述上述情况的另一个更有用的文档:https: //developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Basics#Bracket_notation
Property access via dot walking: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors#Dot_notation
通过 dot walk 访问属性:https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors#Dot_notation
回答by Sergey
You could use lodash _get
function:
你可以使用lodash _get
功能:
var object = { 'a': [{ 'b': { 'c': 3 } }] };
_.get(object, 'a[0].b.c');
// => 3
回答by Andrejs
Using JSONPathwould be one of the most flexible solutions if you are willing to include a library: https://github.com/s3u/JSONPath(node and browser)
如果您愿意包含一个库,使用JSONPath将是最灵活的解决方案之一:https: //github.com/s3u/JSONPath(节点和浏览器)
For your use case the json path would be:
对于您的用例,json 路径为:
$..items[1].name
so:
所以:
var secondName = jsonPath.eval(data, "$..items[1].name");