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

标签 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"
 }
]

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

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

我已经阅读了关于 chunk 的 lodash但没用。

最佳答案

您可以使用 native 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);

关于javascript - 如何使用 lodash/underscorejs 拆分具有特定条件的对象的 javascript 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30645214/

相关文章:

javascript - 如何将图片附加到数组的位置? javascript

xml - 将 XML 转换为 C# 对象

javascript - SweetAlert2 弹出窗口在 .php 文件中不起作用

php - 如何在页面加载后触发 Javascript 函数?

javascript - 我怎样才能让我的脚本工作/响应

javascript - 正则表达式来屏蔽 IBAN

c# - 将值插入数组的有效方法?

c# - 创建一副简单的纸牌 C#

c++ - 动态内存分配给指向对象的指针数组

java arraylist 添加替换而不是添加