How can I access and process nested objects, array

2019-08-20 04:48发布

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?

22条回答
Evening l夕情丶
2楼-- · 2019-08-20 05:25

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.

Object.keys(), Object.values() (ES 2017) and 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].

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

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 loop and destructuring assignment.

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).

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:

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()

The every() method returns true if the specified callback function returns true for every element of the array. The some() method returns true if the specified callback function returns true for some (at least one) element.

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()

The find() methods returns the first element which satisfies the provided callback function. The filter() method returns an array of all elements which satisfies the provided callback function.

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()

The map() method returns an array with the results of calling a provided callback function on the array elements.

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()

The reduce() method reduces an array to a single value by calling the provided callback function with two elements.

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:

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

查看更多
唯我独甜
3楼-- · 2019-08-20 05:26

Using JSONPath would be one of the most flexible solutions if you are willing to include a library: https://github.com/s3u/JSONPath (node and browser)

For your use case the json path would be:

$..items[1].name

so:

var secondName = jsonPath.eval(data, "$..items[1].name");
查看更多
太酷不给撩
4楼-- · 2019-08-20 05:26

Using lodash would be good solution

Ex:

var object = { 'a': { 'b': { 'c': 3 } } };                                                                                               
_.get(object, 'a.b.c');                                                                                             
// => 3  
查看更多
Animai°情兽
5楼-- · 2019-08-20 05:28

If you are looking for one or more objects that meets certain criteria you have a few options using query-js

//will return all elements with an id larger than 1
data.items.where(function(e){return e.id > 1;});
//will return the first element with an id larger than 1
data.items.first(function(e){return e.id > 1;});
//will return the first element with an id larger than 1 
//or the second argument if non are found
data.items.first(function(e){return e.id > 1;},{id:-1,name:""});

There's also a single and a singleOrDefault they work much like firstand firstOrDefaultrespectively. The only difference is that they will throw if more than one match is found.

for further explanation of query-js you can start with this post

查看更多
做自己的国王
6楼-- · 2019-08-20 05:29

A pythonic, recursive and functional approach to unravel arbitrary JSON trees:

handlers = {
    list:  iterate,
    dict:  delve,
    str:   emit_li,
    float: emit_li,
}

def emit_li(stuff, strong=False):
    emission = '<li><strong>%s</strong></li>' if strong else '<li>%s</li>'
    print(emission % stuff)

def iterate(a_list):
    print('<ul>')
    map(unravel, a_list)
    print('</ul>')

def delve(a_dict):
    print('<ul>')
    for key, value in a_dict.items():
        emit_li(key, strong=True)
        unravel(value)
    print('</ul>')

def unravel(structure):
    h = handlers[type(structure)]
    return h(structure)

unravel(data)

where data is a python list (parsed from a JSON text string):

data = [
    {'data': {'customKey1': 'customValue1',
           'customKey2': {'customSubKey1': {'customSubSubKey1': 'keyvalue'}}},
  'geometry': {'location': {'lat': 37.3860517, 'lng': -122.0838511},
               'viewport': {'northeast': {'lat': 37.4508789,
                                          'lng': -122.0446721},
                            'southwest': {'lat': 37.3567599,
                                          'lng': -122.1178619}}},
  'name': 'Mountain View',
  'scope': 'GOOGLE',
  'types': ['locality', 'political']}
]
查看更多
孤傲高冷的网名
7楼-- · 2019-08-20 05:30

You can access it this way

data.items[1].name

or

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

Both ways are equal.

查看更多
登录 后发表回答