繁体   English   中英

将具有(可能嵌套的)数组的对象转换为具有单项数组的对象的数组

[英]Turn object with (possible nested) arrays into an array of objects with single-item arrays

我试图创建一个可以打开此数组的递归函数:

const originalObj = {
    field: "parent",
    msg:[{
        field: "child1a",
        msg: [{
            field: "child2a",
            msg: "child2a-msg"
        },
        {
            field: "child2b",
            msg: "child2b-msg"
        }
      ]
    }, {
        field: "child1b",
        msg: "child1b-msg"
    }
  ]
};

进入这一个:

[
    {
    field: "parent",
    msg: [
      {
        field: "child1a",
        msg: [
          {
            field: "child2a",
            msg: "child2a-msg"
          }
        ]  
      },
    ]
    },
  {
    field: "parent",
    msg: [
      {
        field: "child1a",
        msg: [
          {
            field: "child2b",
            msg: "child2b-msg"
          }
        ]  
      },
    ]
    },
  {
    field: "parent",
    msg: [
        {
        field: "child1b",
        msg: "child1b-msg"
      }
    ]
  }
]

因此,需要明确的是:msg对象可以是字符串或单个项目数组。

它应该是递归的; 因为msg对象可以包含一个数组,而该数组可以包含更深的msg对象,可以包含另一个数组,依此类推。

这是我的尝试,但我无法解决。 https://jsfiddle.net/rnacken/42e7p8hz/31/

正如您在小提琴中看到的那样,数组是嵌套的,缺少父级,而我缺少一个孩子。 恐怕我迷路了,走错了路。

您可以迭代msg并为嵌套项目构建新的嵌套零件结果。 然后迭代并为结果数组构建单个对象。

 function getSingle({ field, msg }) { var array = []; if (!msg || !Array.isArray(msg)) { return [{ field, msg }]; } msg.forEach(o => getSingle(o).forEach(s => array.push({ field, msg: [s] }))); return array; } var object = { field: "parent", msg: [{ field: "child1a", msg: [{ field: "child2a", msg: [{ field: "child3a", msg: "child3a-msg" }, { field: "child3b", msg: "child3b-msg" }] }, { field: "child2b", msg: "child2b-msg" }] }, { field: "child1b", msg: "child1b-msg" }] }; console.log(getSingle(object)); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

我添加了一个可以使用的简单递归方法。

const originalObj = {
    field: "parent",
    msg: [
    {
        field: "child1a",
        msg: [
        {
            field: "child2a",
            msg: "child2a-msg"
        },
        {
            field: "child2b",
            msg: "child2b-msg"
        }
      ]
    },
    {
      field: "child1b",
      msg: "child1b-msg"
    }
  ]
};

const flatten = ({field, msg}) =>  {
    const res = []; // creating an array to create the msg array in case of multiple entries in msg
    if (typeof msg === "string") {
        return {field, msg}; // return plain object if the msg is "string"
    }
    if (msg.constructor === Array) {
        // recursion here
        msg.map(message => flatten(message, msg))
        .forEach(m => {
            // after flattening array msg, we push them to msg field
            res.push({field, msg: m})
        });
    }
    return res; // returning final result here
}
const newObj = flatten(originalObj);

使用flatten功能,您可以映射阵列的任何深度并获得相同的结果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM