我有一个看起来像这样的对象:
var someUglyObject =
{
"1-1" : {foo1: "foo1-1Value", bar1: "bar1-1value"},
"1-2" : {foo2: "foo1-2Value", bar2: "bar1-2value"},
"2-1" : {foo2: "foo2-1Value", bar2: "bar2-1value"},
"2-2" : {foo2: "foo2-2Value", bar2: "bar2-2value"}
}
我需要简化上面的嵌套对象,并在进行如下处理(连接)后将其转换为更简单的对象:
var myObj = {
"1": { propsTogether : "foo1-1Valuebar1-1valuefoo1-2Valuebar1-2value"},
"2": { propsTogether : "foo2-1Valuebar2-1valuefoo2-2Valuebar2-2value" }
}
我的计划是像这样遍历所有关键点,但不确定如何根据关键点的第一个字符将道具分组在一起,即对于值为'2-1'的关键点-2应该是新的键。
var myObj= {};
Object.keys(someUglyObject).forEach(function(key) {
}
答案 0 :(得分:1)
您可以使用Object.keys
和reudce
这里的想法是
-
上拆分键,并使用first element
作为op
对象上的键。
var obj = {'1-1' : {foo1: "foo1-1Value", bar1: "bar1-1value"},'1-2' : {foo2: "foo1-2Value", bar2: "bar1-2value"},'2-1' : {foo2: "foo2-1Value", bar2: "bar2-1value"},'2-2' : {foo2: "foo2-2Value", bar2: "bar2-2value"}}
let op = Object.keys(obj).sort().reduce((op,inp)=>{
let key = inp.split('-',1)[0]
op[key] = op[key] || {props:''}
op[key].props = op[key].props + Object.values(obj[inp]).join('')
return op
},{})
console.log(op)