Hao's Blog

Software Engineer

Extract Values From Javascript Nested Object

| Comments

Underscore doesn’t support search and find nested value in a nested javascript object, So I went ahead and built a version for that:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# This helper is served to relieve the efforts of building up external formatted object through
# nested object which we retrieve from mongoDB or http params
# Usage:
#     SampleData =
#       token: '1234',
#       user:
#         token: '4321'
#       contact:
#         address:
#           city: 'Emeryville'
#           state: 'CA'
#           zip_code: '51421'

# All we need to do is
# Helper.DataPicker(SampleData, 'token', 'user.token', 'city')
# For nested key with the duplicated names, we need to nest the top parents nodes as well.
# For example 'user.token'

_ = require 'underscore'

DataPicker = (data, attributes...) ->

  result = {}

  # Loop through each pair of data and find the matching attributes
  _.each data, (value, key, list) ->
    if _.contains(attributes, key) and (!_.isObject(list[key]) or _.isArray(value))
      result[key] ||= value
    else if _.isObject(value) and !_.isArray(value)
      for subKey, subValue of value
        arguments.callee(subValue, subKey, value)

  # Loop through nested cases like user.token, merchant.token
  _.each attributes, (attribute) ->
    if attribute.match(/^[a-z]+[.]/)
      keys = attribute.split('.')
      element = keys.join('_')
      nestedElement = _.reduce(keys, (memo, num) ->
        if !_.isUndefined(memo)
          memo = memo[num]
      , data)

      result[element] = nestedElement if !_.isUndefined(nestedElement)

  return result

module.exports = DataPicker

Comments