简体   繁体   English

将字符串数组转换为JS中的一个对象

[英]Convert array of arrays of strings to one object in JS

Let's say that I have the following array: 假设我有以下数组:

[
 {
   path: ["info", "address", "city"]
 },
 {
   path: ["info", "first_name"]
 },
 {
   path: ["info", "last_name"]
 },
 {
   path: ["score"]
 }
]

And I want to convert this to: 我想将其转换为:

{
  personal_info: {
    first_name: some_value,
    last_name: some_value,
    adress: {
     city: some_value
    }
  },
  score: some_value
}

Note: some_value is just another key represented before path key. 注意:some_value只是在路径键之前表示的另一个键。

I have tried something in this structure: 我已经尝试过这种结构的东西:

for(let i = a.length - 1; i >= 0 ; i--){
  if(i == a.length - 1)
    res = { [a[i]] : value};        // assign the value
  else
    res = { [a[i]] : res};          //put the prev object
}

However I don't know how to concatenate from multiple arrays to one object. 但是我不知道如何从多个数组连接到一个对象。

You can use either the function reduce or the function forEach to build that desired output. 您可以使用reduce函数或forEach函数构建所需的输出。

This approach uses the function reduce , and for the specific values you need to decide how to set them. 这种方法使用了reduce函数,对于特定的值,您需要决定如何设置它们。

 let arr = [ { path: ["info", "address", "city"] }, { path: ["info", "first_name"] }, { path: ["info", "last_name"] }, { path: ["score"] }], value = 'some_value', personalInfoKey = 'personal_info', result = arr.reduce((a, {path}) => { let [type, ...keys] = path; if (type === 'info') { if (keys.length === 1) a[personalInfoKey][keys.pop()] = value; else { a[personalInfoKey] = a[personalInfoKey] || {}; let current = a[personalInfoKey]; keys.forEach((k, i, ar) => current = current[k] = i === ar.length - 1 ? value : {}); } } else a[type] = value; return a; }, {}); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

You can use 2 reduce s. 您可以使用2 reduce s。 The first one is to loop thru the array. 第一个是通过数组循环。 The second one is to construct the result object. 第二个是构造结果对象。

 var arr = [ {"path":["info","address","city"],"value":1}, {"path":["info","first_name"],"value":2}, {"path":["info","last_name"],"value":3}, {"path":["score"],"value":4} ] var result = arr.reduce((c, v) => { var t = v.path.reduce((a, o, i) => { o = o === "info" ? "personal_info" : o; if (i < v.path.length - 1 && !a[o]) a[o] = {}; if (i < v.path.length - 1) return a[o]; else return a; }, c); t[v.path[v.path.length - 1]] = v.value; return c; }, {}); console.log(result); 

You could iterate the array and reduce the keys with default object for assigning the vlaue. 您可以迭代数组并使用默认对象来减少键,以分配vlaue。

 function setValue(object, path, value) { var last = path.pop(); path.reduce((o, k) => o[k] = o[k] || {}, object)[last] = value; return object; } var data = [{ value: "Düsseldorf", path: ["info", "address", "city"] }, { value: "Jane", path: ["info", "first_name"] }, { value: "Smith", path: ["info", "last_name"] }, { value: 11000, path: ["score"] }], object = data.reduce((o, { path, value }) => setValue(o, [...path], value), {}); console.log(object); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

 const data = [ { path: ["info", "address", "city"] }, { path: ["info", "first_name"] }, { path: ["info", "last_name"] }, { path: ["score"] } ]; const newObject = {}; function setValueByKeypath(currentObject, path, value) { for (let i = 0, len = path.length; i < len; i++) { const key = path[i]; // if it is the last path part, add the value else we have to got on building objects const keyValue = (i === len - 1) ? value : {}; // test if there is already a given key and if not create one or if it is the last part of the key add the value if (typeof currentObject[key] === "undefined") { currentObject[key] = keyValue; } currentObject = currentObject[key]; } } for (let i = 0, len = data.length; i < len; i++ ) { // build the nested path in the object by the given array data[i].path setValueByKeypath(newObject, data[i].path, "someValue"); } console.log(newObject); // create a reference 'personal_info' to 'info' newObject.personal_info = newObject.info; // delete the 'info' key delete newObject.info; console.log(newObject); 

First go through those paths. 首先走那些路。 And secondly turn the info key into a personal_info key. 然后将信息密钥转换为personal_info密钥。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM