如何在JavaScript中使用mapKeys和按键分组值?

时间:2018-08-09 23:30:34

标签: javascript json object mapping lodash

最初,我有一个对象:

let root = {};
root["myRootNode"] = { 
   id1: {
     age: "17",
     name: "name1",
     surname: "surname1"                    
  },
   id2: {
     age: "11",
     name: "name2",
     surname: "surname2"                    
  },
   id3: {
     age: "25",
     name: "name1",
     surname: "surname3"                    
  }
};

我想做的就是让它进入状态:

"name1": [
  {
     age: "17",
     surname: "surname1"         
  },
  {
     age: "25",
     surname: "surname3"         
  }
],
"name2": [
    age: "11",
    surname: "surname2"        
]

对我来说,重要的是,所有对象的列表/数组都包含相同的属性,并按该属性的值分组。

我尝试过(使用lodash)是:

let test = _.mapKeys(root["myRootNode"], function(value, key) {
  return value["name"];
});

但这给了我结果:

"name1": {
   age: "25"
   name: "name1"
   surname: "surname3"
},
"name2": {
   age: "11"
   name: "name2"
   surname: "surname2"
}

因此,它们没有分组,只有最后一个值映射在重复的键下。同样,根据我得到的结果,它们没有放置在数组下。

2 个答案:

答案 0 :(得分:1)

这里有一个镜头。想法是为每个新名称创建一个数组,然后将所有条目推入相应的名称数组。

const root = {
  myRootNode: {
    id1: {
      age: "17",
      name: "name1",
      surname: "surname1"
    },
    id2: {
      age: "11",
      name: "name2",
      surname: "surname2"
    },
    id3: {
      age: "25",
      name: "name1",
      surname: "surname3"
    }
  }
};

const result = Object.values(root.myRootNode).reduce((a, e) => {
  if (!(e.name in a)) {
    a[e.name] = [];
  }

  a[e.name].push({
    age: e.age,
    surname: e.surname
  });

  return a;
}, {});

console.log(JSON.stringify(result, null, 4));

答案 1 :(得分:1)

可以使用groupBy并映射其值来摆脱name属性。

如果您不介意离开name属性,只需执行_.groupBy(root.myRootNode, 'name');

个人感觉您应该使用数组而不是对象

const res =
_(root.myRootNode)
  .groupBy('name')
  .mapValues((arr)=>_.map(arr, (o) =>_.omit(o,['name'])))
  .value()



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

<script>
let root = {};
root["myRootNode"] = { 
   id1: {
     age: "17",
     name: "name1",
     surname: "surname1"                    
  },
   id2: {
     age: "11",
     name: "name2",
     surname: "surname2"                    
  },
   id3: {
     age: "25",
     name: "name1",
     surname: "surname3"                    
  }
};
</script>