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

问题描述 投票:6回答:5

我有这样的对象数组:

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但它没用。

javascript arrays object underscore.js lodash
5个回答
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);

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)

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/


0
投票
for (ele in data)
{
    if (!data[ele].hasOwnProperty('child') && data[ele].type=='parent')
    {
        data[ele].child = [];
        while(data[parseInt(ele) + 1] && data[parseInt(ele) + 1].type == 'child')
        {
            data[ele].child.push({type: data[parseInt(ele) + 1].type, name:data[parseInt(ele) + 1].name});
            data.splice(parseInt(ele) + 1, 1);
        }
    }
}
console.log(data);

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

© www.soinside.com 2019 - 2024. All rights reserved.