求助大佬,关于数组用JS改变数据格式问题?
一个数据格式是这样的:
a:[ [{id: "12", lottery_id: "1", type_id: "37", type: "commodity", image: "XX.jpg"}],
[{id: "11", lottery_id: "1", type_id: "37", type: "commodity", image: "XX.jpg"}],
]
把他转换成这样
b:[ { fonts: [{ text: '0', top: '10%', id: "12", lottery_id: "1",}],image: "XX.jpg" },
{ fonts: [{ text: '1', top: '10%', id: "11", lottery_id: "2",}],image: "XX.jpg" },
]
用JS需要怎么做?
回答:
let a = [ [{ id: "12", lottery_id: "1", type_id: "37", type: "commodity", image: "XX.jpg" }],
[{ id: "11", lottery_id: "1", type_id: "37", type: "commodity", image: "XX.jpg" }],
];
let b = a.map(([{ id, lottery_id, image }], index) => ({
fonts: [
{
text: String(index),
top: "10%",
id,
lottery_id,
},
],
image,
}));
回答:
<script> const data = {
a: [
[{ id: "12", lottery_id: "1", type_id: "37", type: "commodity", image: "XX.jpg" }],
[{ id: "11", lottery_id: "1", type_id: "37", type: "commodity", image: "XX.jpg" }]
]
};
// 转换数据格式
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.jpg" }],
[{ id: "11", lottery_id: "1", type_id: "37", type: "commodity", image: "XX.jpg" }],
]
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.jpg"
}],
[{
id: "11",
lottery_id: "1",
type_id: "37",
type: "commodity",
image: "XX.jpg"
}],
];
const b = a.map(([{
id,
image
}], i) => ({
fonts: [{
id,
text: i + "",
top: "10%",
lottery_id: ++i + ""
}],
image
}));
console.log(b);
以上是 求助大佬,关于数组用JS改变数据格式问题? 的全部内容, 来源链接: utcz.com/p/934467.html