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



我正在尝试创建一个可以转动此数组的递归函数:

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函数,您可以映射数组的任何深度并期望相同的结果。

最新更新