求助大佬,关于数组用JS改变数据格式问题?

一个数据格式是这样的:

a:[
    [{id: "12", lottery_id: "1", type_id: "37", type: "commodity", image: "XX.png"}],
    [{id: "11", lottery_id: "1", type_id: "37", type: "commodity", image: "XX.png"}],
]

把他转换成这样

b:[
    { fonts: [{ text: '0', top: '10%', id: "12", lottery_id: "1",}],image: "XX.png" },
    { fonts: [{ text: '1', top: '10%', id: "11", lottery_id: "2",}],image: "XX.png" },
]

用JS需要怎么做?

阅读 2k
4 个回答
let a = [
    [{ id: "12", lottery_id: "1", type_id: "37", type: "commodity", image: "XX.png" }],
    [{ id: "11", lottery_id: "1", type_id: "37", type: "commodity", image: "XX.png" }],
];
let b = a.map(([{ id, lottery_id, image }], index) => ({
    fonts: [
        {
            text: String(index),
            top: "10%",
            id,
            lottery_id,
        },
    ],
    image,
}));

image.png

<script>

  const data = {
    a: [
      [{ id: "12", lottery_id: "1", type_id: "37", type: "commodity", image: "XX.png" }],
      [{ id: "11", lottery_id: "1", type_id: "37", type: "commodity", image: "XX.png" }]
    ]
  };

  // 转换数据格式
  const transformedData = {
    b: data.a.map((subArray, index) => {
      const { id, lottery_id, image } = subArray[0];
      return {
        fonts: [{ text: index.toString(), top: '10%', id, lottery_id }],
        image
      };
    })
  };

  console.log(transformedData);

</script>

<!DOCTYPE html>
<html lang="en">

<head>

<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>

</head>

<body>

<script>
    let a = [
        [{ id: "12", lottery_id: "1", type_id: "37", type: "commodity", image: "XX.png" }],
        [{ id: "11", lottery_id: "1", type_id: "37", type: "commodity", image: "XX.png" }],
    ]
    let b = a.map((item, index) => {
        let { id, lottery_id, image } = item[0]
        let fonts = []
        let obj2 = {}
        obj2.text = index.toString()
        obj2.top = '10%'
        obj2.id = id
        obj2.lottery_id = (index + 1).toString()
        fonts.push(obj2)
        return { fonts, image: image }
    })
    console.log(b)
</script>

</body>

</html>

const a = [
    [{
        id: "12",
        lottery_id: "1",
        type_id: "37",
        type: "commodity",
        image: "XX.png"
    }],
    [{
        id: "11",
        lottery_id: "1",
        type_id: "37",
        type: "commodity",
        image: "XX.png"
    }],
];
const b = a.map(([{
    id,
    image
}], i) => ({
    fonts: [{
        id,
        text: i + "",
        top: "10%",
        lottery_id: ++i + ""
    }],
    image
}));
console.log(b);
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏