簡體   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