[英]Converting nested arrays to objects
[["seller" , [["id" , "1"], ["name", "test"]]], ["token", "aasfgsgd"], ["settings", [["general", false], ["store", [["trusted", true], ["socialMedia", [["fbConnected", true], ["igConnected", false]]]]]]]]
This nested array can be variable, So convert it into an Object like shown below这个嵌套数组可以是可变的,因此将其转换为如下所示的对象
{
"seller": {
"id": 1,
"name": "test"
},
"token": "aasfgsgd",
"settings": {
"general": false,
"store": {
"trusted": true,
"socialMedia": {
"fbConnected": true,
"igConnected": false
}
}
}
}
You can use Object.fromEntries()
with a recursive function to convert all nested [[key, value], ...]
pair arrays into objects themselves.您可以使用带有递归函数的Object.fromEntries()
将所有嵌套的[[key, value], ...]
对数组转换为对象本身。
The Object.fromEntries()
method is able to take an array such as: Object.fromEntries()
方法能够接受一个数组,例如:
[["key", "val2"]]
... and convert it into an object: ...并将其转换为对象:
{
"key": "val2"
}
However, if "val2"
is an array itself, this would need to be converted into an object first.但是,如果"val2"
本身是一个数组,则需要先将其转换为对象。 This can be done by recursively calling Object.fromEntries()
on the value entries which are arrays.这可以通过对作为数组的值条目递归调用Object.fromEntries()
来完成。
See example below:请参阅下面的示例:
const arr = [["seller" , [["id" , 1], ["name", "test"]]], ["token", "aasfgsgd"], ["settings", [["general", false], ["store", [["trusted", true], ["socialMedia", [["fbConnected", true], ["igConnected", false]]]]]]]]; const makeObject = arr => { return Object.fromEntries(arr.map( ([key, val]) => Array.isArray(val) ? [key, makeObject(val)] : [key, val] )); } console.log(makeObject(arr));
A more browser-friendly approach would be to use .reduce()
with the spread syntax instead of Object.fromEntries()
:一种对浏览器更友好的方法是使用.reduce()
和扩展语法而不是Object.fromEntries()
:
const arr = [["seller" , [["id" , 1], ["name", "test"]]], ["token", "aasfgsgd"], ["settings", [["general", false], ["store", [["trusted", true], ["socialMedia", [["fbConnected", true], ["igConnected", false]]]]]]]]; const makeObject = arr => { return arr.reduce((o, [key, val]) => { return Object.assign(o, {[key]: Array.isArray(val) ? makeObject(val) : val}); }, {}); } console.log(makeObject(arr));
const array = [["seller" , [["id" , "1"], ["name", "test"]]], ["token", "aasfgsgd"], ["settings", [["general", false], ["store", [["trusted", true], ["socialMedia", [["fbConnected", true], ["igConnected", false]]]]]]]]; function objectify(arr) { return arr.reduce((acc, item) => { let builder; if (Array.isArray(item[0])) { builder = objectify(item[0]) } else { const propName = item[0]; const propValue = Array.isArray(item[1]) ? objectify(item[1]) : item[1]; builder = {[propName]: propValue}; } return { ...acc, ...builder } }, {}); } console.log(objectify(array));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.