如何使用lodash / underscorejs拆分具有特定条件的javascript对象数组

时间:2015-06-04 13:32:53

标签: javascript arrays object underscore.js lodash

我有这样的对象数组:

var data = [
 {
    type : "parent",
    name : "A"
 },
 {
    type : "child",
    name : "1"
 },
 {
    type : "child",
    name : "2"
 },
 {
    type : "parent",
    name : "B"
 },
 {
    type : "child",
    name : "3"
 }
]

我希望将子对象移动到父对象中,由parrent对象分割(没有来自子对象的给定键属于哪个parrent)。所以它只与父对象分开。为简单起见,我想将数组更改为:

[
  {
    type : "parent",
    name : "A",
    child: [
        {
            type : "child",
            name : "1"
        },
        {
            type : "child",
            name : "2"
        }
    ]
  },
  {
    type : "parent",
    name : "B",
    child: [
        {
            type : "child",
            name : "3"
        }
      ]
  }
]

我已阅读关于chunk的lodash,但这没用。

5 个答案:

答案 0 :(得分:9)

您可以使用原生Array.prototype.reduce功能或lodash' reduce



var data = [{
    type: "parent",
    name: "A"
  },
  {
    type: "child",
    name: "1"
  },
  {
    type: "child",
    name: "2"
  },
  {
    type: "parent",
    name: "B"
  },
  {
    type: "child",
    name: "3"
  }
];

// If using _.reduce then use:
// var newData = _.reduce(data, function(arr, el) {...}, []);
var newData = data.reduce(function(arr, el) {
  if (el.type === 'parent') {
    // If el is pushed directly it would be a reference
    // from the original data object
    arr.push({
      type: el.type,
      name: el.name,
      child: []
    });
  } else {
    arr[arr.length - 1].child.push({
      type: el.type,
      name: el.name
    });
  }

  return arr;
}, []);

console.log(newData);




更新:使用较新的ES语言功能进行小更改



const data = [{
    type: "parent",
    name: "A"
  },
  {
    type: "child",
    name: "1"
  },
  {
    type: "child",
    name: "2"
  },
  {
    type: "parent",
    name: "B"
  },
  {
    type: "child",
    name: "3"
  }
];

const newData = data.reduce((arr, el) => {
  if (el.type === 'parent') {
    // If el is pushed directly it would be a reference
    // from the original data object
    arr.push({...el, child: []});
  } else {
    arr[arr.length - 1].child.push({...el});
  }

  return arr;
}, []);

console.log(newData);




答案 1 :(得分:2)

这是一个可能更容易理解的lodash解决方案。 CodePen

一些注意事项:

  • 这会修改传入的数据对象 - 如果这是一个问题,我们可以进行一些_.clone()次调用。
  • 只有在每个家长有26个或更少孩子的情况下才会生效,因为您选择了name: "ab"模式
var lastParent;
var result = _.chain(data)
  .groupBy(function (item) {
    if (item.type === 'parent') lastParent = item.name
    return lastParent
  })
  .map(function (group) {
    var parent = _.first(group)
    parent.child = _.chain(group)
      .slice(1)
      .map(function (child, index) {
        child.name = parent.name.toLowerCase() + String.fromCharCode(index + 97)
        return child 
      })
      .value()
    return parent
  })
  .value()

console.log(result)

答案 2 :(得分:0)

普通的javascript版本:

var newArr = [];
var j=0;
var k=0;
for (var i = 0; i <data.length; i++) {
    if(data[i].type == 'parent'){
        newArr[j] = data[i];
        newArr[j].children = [];
        j++;
        k=0;
    } 
    else {
        data[i].name = newArr[j-1].name.toLowerCase() + String.fromCharCode(k + 97)
        newArr[j-1].children[k] =data[i];
        k++;
    }
}
console.log(newArr)

我假设父母的总是放在孩子面前,如示例数据所示。

此外,如果您可以阻止有26个以上孩子的父母,那将是一件好事。这会导致String.fromCharCode(k + 97)打印奇怪的字符。为此,请参阅http://www.asciitable.com/

答案 3 :(得分:0)

g++

答案 4 :(得分:0)

尝试简单循环:

var current, parent, result = [], i = 0;

while(current = data[i++]){

    if(current.type === "parent"){
        current.child = [];
        result.push(current);
        parent = current
    }else{
        current.name = (parent.name + String.fromCharCode(parent.child.length + 97)).toLowerCase();
        parent.child.push(current)
    }

}

<强> Demo