将对象数组转换为嵌套形式

时间:2016-11-06 16:53:34

标签: angularjs node.js mongodb

我有一个这种形式的对象数组

nnz=[{

    "verb":"has",

     "nouns": "employees"
   },

   {

     "verb":"has",
     "nouns": "managers"
   },

    {

    "verb":"have",
     "nouns": "departments"
   }
]

但我想将其转换为此形式

[ {

     "verb":"has",
     "nouns": ["employees",  "managers"]
   },

   {
    "verb":"have",
    nouns:["departments"]
  }
]

这项工作必须从客户端完成。我在node.js工作。我想允许用户针对每个动词选择多个名词,当用户选择动词的名词时,它应该保存到上面给定形式的数组中。我无法弄明白我该如何实现这个逻辑。

更新: 我们也必须检查动词。现在它变得更加棘手。

3 个答案:

答案 0 :(得分:0)

你可以使用一些Array内置函数来做这样的事情:

const array = [

  {

    "verb":"has",

     "nouns": "employees"
   },

   {

     "verb":"has",
     "nouns": "managers"
   },

    {

    "verb":"has",
     "nouns": "departments"
   }
]

const aggregated = array.reduce( (arr, el) =>{
  let found = arr.find(ll => ll.verb == el.verb);
  if(found) found.nouns.push(el.nouns);
  else arr.push({verb : el.verb, nouns : [el.nouns] })
  return arr;
}, []);
console.log(aggregated);

答案 1 :(得分:0)

首先创建一个临时对象,该对象使用动词值作为键,然后迭代现有数据,将名词推到该临时对象中的相应数组。

然后将临时对象映射到新数组。

nnz = [{
  "verb": "has",
  "nouns": "employees"
}, {
  "verb": "has",
  "nouns": "managers"
}, {
  "verb": "has",
  "nouns": "departments"
}]

var tmp = {};
nnz.forEach(function(item) {
  tmp[item.verb] = tmp[item.verb] || {
    verb: item.verb,
    nouns: []
  };
  tmp[item.verb].nouns.push(item.nouns);
});

var results = Object.keys(tmp).map(function(key) {
  return tmp[key];
});

console.log(results);

答案 2 :(得分:0)

根据您的要求尝试这两种方法。我希望它能按照期望

运作

第一种方法:

当您知道属性名称时:

var nnz = [{
"verb":"has",
 "nouns": "employees"
   },
   {
 "verb":"has",
 "nouns": "managers"
   },
{
"verb":"has",
 "nouns": "departments"
   }
];

var newObj = {};
var nouns = [];
for (var i in nnz) {
nouns.push(nnz[i].nouns);
newObj.verb = nnz[i].verb;
newObj.nouns = nouns;
}
  
nnz = newObj;

console.log(nnz);

第二种方法:

当您不知道属性名称时:

var nnz = [{
    "verb":"has",
     "nouns": "employees"
   },
   {
     "verb":"has",
     "nouns": "managers"
   },
    {
    "verb":"has",
     "nouns": "departments"
   }
];

var newObj = {};
var nounsArr = [];
for (var i in nnz) {
nounsArr.push(nnz[i][Object.keys(nnz[i])[1]])
nnz[i][Object.keys(nnz[i])[1]] = nounsArr;
var Objlen = Object.keys(nnz[i]).length;
for (var j=0;j<Objlen;j++) {
var objKeys = Object.keys(nnz[i])[j];
newObj[objKeys] = nnz[i][objKeys];
}
}

nnz = newObj;

console.log(nnz);