Javascript dotted object keys to object

时光怂恿深爱的人放手 提交于 2019-12-22 08:12:13

问题


How do you convert a dotted keys into a javascript object and retain it's value?

So I got this kind of response from an API and I need to parse it by key: value.

{
  "property": "personal_info.address.city",
  "description": "Missing field"
},
{
  "property": "personal_info.address.country",
  "description": "Missing field"
},

So I achieved this:

{
    'personal_info.address.city': 'Missing field',
    'personal_info.address.country': 'Missing field'
}

// by using this code (lodash)

_.mapValues(_.keyBy(obj, 'property'), function(o) {
  return o.description;
})

however, i need it to be like this:

{
    personal_info: {
        address: {
            city: 'Missing field',
            country: 'Missing field',
        }
    }
}

I somehow searched in stackoverflow how to convert a dot notation string into an object here: Convert string with dot notation to JSON

but I'm stuck since I'm changing the key itself.

EDIT: Changed test city and test country to reflect the description field (sorry)


回答1:


You could use _.set from lodash.

Sets the value at path of object. If a portion of path doesn't exist, it's created. Arrays are created for missing index properties while objects are created for all other missing properties. Use _.setWith to customize path creation.

var array = [{ property: "personal_info.address.city", description: "Missing field" }, { property: "personal_info.address.country", description: "Missing field" }],
    object = array.reduce((o, { property, description }) => _.set(o, property, description), {});

console.log(object);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>



回答2:


You could use forEach() loop and inside reduce() method to get result like this.

const data = [{"property": "personal_info.address.city","description": "Missing field"},{"property": "personal_info.address.country","description": "Missing field"}]

const result = {}
data.forEach(function(o) {
  o.property.split('.').reduce(function(r, e, i, arr) {
    return r[e] = (r[e] || (arr[i + 1] ? {} : o.description))
  }, result)
})

console.log(result)


来源:https://stackoverflow.com/questions/49302780/javascript-dotted-object-keys-to-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!