簡體   English   中英

如何在 JSON 中移動和映射對象。 在 Javascript 中

[英]How to move and map objects within a JSON. In Javascript

我有一個問題,我正在嘗試在 JSON 中移動對象。

我目前正在使用 Javascript/React 並願意使用 lodash。

這是以下 JSON。

{
  "data1": [
    { "status": "off", "height": 12 },
    { "status": "on" , "height":  4 }
  ],
  "data2": [
    { "status": "off", "height": 24 },
    { "status": "on" , "height":  4 }
  ],
  "data3": [
    { "status": "off", "height": 12 },
    { "status": "on" , "height":  5 },
    { "status": "off", "height":  5 }
  ],
  "data4": [],
  "data5": [
    { "status": "on" , "height":  5 },
    { "status": "off", "height": 50 },
    { "status": "on" , "height": 50 }
  ]
}

我的問題:每個“dataX”都必須以“on”狀態開始並以“off”狀態結束,如果“datax”第一個條目是“status”:“off”,則需要將其轉移到 JSON 數組之前. 這包括在映射“data5”時它應該轉移到“data1”

因此,我試圖實現的最終結果是,所有值都正確移動:

{
  "data1": [
    { "status": "on" , "height": 50 },
    { "status": "off", "height": 12 },
    { "status": "on" , "height":  4 },
    { "status": "off", "height": 24 }
  ],
  "data2": [
    { "status": "on" , "height":  4 },
    { "status": "off", "height": 12 }
  ],
  "data3": [
    { "status": "on" , "height":  5 },
    { "status": "off", "height":  5 }
  ],
  "data4": [],
  "data5": [
    { "status": "on" , "height":  5 },
    { "status": "off", "height": 50 }
  ]
}

我希望這是有道理的?

我試圖開始“映射” JSON object.values 然后過濾,但我剛剛陷入困境。

任何幫助深表感謝。

編輯:

這就是我到目前為止所擁有的,它發現包含“off”的第一個元素的所有實例都將它從數組中拼接起來。 然后將其存儲在另一個數組中。

因此現在有兩個數組,如果原始(現在修改)包含“off”,則刪除其第一個位置。

第二個數組存儲這些刪除的項目。

然后我希望將這些項目向上移動一個數組索引。

const newdb = Object.entries(data);

const original = newdb.map((item) => ({
  name: item[0],
  data: item[1],
}));

const cutout = newdb.map((item) => ({
  name: item[0],
  data:
    item[1][0] && item[1][0].status === "off" ? item[1].splice(0, 1) : [],
}));

此答案假定條目始終具有交替狀態。

 const dataMap = { data1: [ { status: "off", height: 12 }, { status: "on", height: 4 }, ], data2: [ { status: "off", height: 24 }, { status: "on", height: 4 }, ], data3: [ { status: "off", height: 12 }, { status: "on", height: 5 }, { status: "off", height: 5 }, ], data4: [], data5: [ { status: "on", height: 5 }, { status: "off", height: 50 }, { status: "on", height: 50 }, ], }; const dataArr = Object.values(dataMap) dataArr.forEach((item, index) => { if (index === 0 || item.length == 0) return if (item[0].status === "off") { const prevItem = dataArr[index-1] const entry = item.splice(0, 1)[0] prevItem.push(entry) } if (index == dataArr.length-1) { if (item[item.length-1].status === "on") { const entries = [...item.splice(item.length-1, 1), ...dataArr[0]] dataArr[0].splice(0, dataArr[0].length, ...entries) // change the contents of data1 note that data1 still points to the same array after this operation } } }) console.log(dataMap)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM