我有一个问题我一直没能解决,基本上我想改变这个:
{
"seamark:name": "Z-2",
"seamark:type": "buoy_lateral",
"seamark:light:range": "5",
"seamark:light:colour": "red",
"seamark:light:character": "Q",
"seamark:radar_reflector": "yes",
"seamark:buoy_lateral:shape": "can",
"seamark:buoy_lateral:colour": "red",
"seamark:buoy_lateral:system": "iala-a",
"seamark:buoy_lateral:category": "port"
}这方面:
{
seamark: {
name: "Z-2",
type: "buoy_lateral",
light: {
range: "5",
colour: "red",
reflector: "yes"
},
buoy_lateral: {
shape: "can",
colour: "red",
system: "iala-a",
category: "port
}
}
}现在,我只实现了一个包含10个对象的数组,每次使用以下链接中显示的代码(例如,{seamark:{name:“Z-2”})到值的路径都是这样的:码页
一旦我在代码页中显示了结果,有人会想到如何对属性进行深度分组吗?或者甚至是另一个主意?提前感谢
发布于 2018-11-16 14:02:47
您正在尝试unflat一个对象。
您可以使用flat npm (https://www.npmjs.com/package/flat)
const { unflatten } = require('flat');
const unflat = unflatten({
"seamark:name": "Z-2",
"seamark:type": "buoy_lateral",
"seamark:light:range": "5",
"seamark:light:colour": "red",
"seamark:light:character": "Q",
"seamark:radar_reflector": "yes",
"seamark:buoy_lateral:shape": "can",
"seamark:buoy_lateral:colour": "red",
"seamark:buoy_lateral:system": "iala-a",
"seamark:buoy_lateral:category": "port"
}, { delimiter: ":" }); // notice delimiter : default is "."
console.log(unflat);输出:
{
seamark: {
name: 'Z-2',
type: 'buoy_lateral',
light: { range: '5', colour: 'red', character: 'Q' },
radar_reflector: 'yes',
buoy_lateral:
{
shape: 'can',
colour: 'red',
system: 'iala-a',
category: 'port'
}
}
}发布于 2018-11-16 20:27:12
您还可以使用"for..of“和"Array.reduce”,如下所示
var obj = {
"seamark:name": "Z-2",
"seamark:type": "buoy_lateral",
"seamark:light:range": "5",
"seamark:light:colour": "red",
"seamark:light:character": "Q",
"seamark:radar_reflector": "yes",
"seamark:buoy_lateral:shape": "can",
"seamark:buoy_lateral:colour": "red",
"seamark:buoy_lateral:system": "iala-a",
"seamark:buoy_lateral:category": "port"
}
let newObj = {}
for(let [key, val] of Object.entries(obj)) {
let keys = key.split(':')
keys.reduce((o, d, i) => (
i == keys.length - 1
? (o[d] = val)
: (o[d] = o[d] || {})
, o[d])
, newObj)
}
console.log(newObj)
https://stackoverflow.com/questions/53339230
复制相似问题