我有大量的json对象,我需要对其进行迭代并将其添加到另一个json数组中。
该数组如下所示-
{
id : 1,
name : "test1",
location : "London",
cost: "120.83"
},
{
id : 2,
name : "test2",
location : "shanghai",
cost: "124.83"
},
{
id : 3,
name : "test3",
location : "Barcelona",
cost: "56.54"
}
im使用的实际数组具有73个键,值对和大约20000个对象。
我正在尝试将每个对象转换为另一个数组,该数组看起来应该像-
{
cells:
[
{
value: 1,
textAlign: "center",
background: "rgb(255,255,255)",
color: "rgb(0,62,117)"
},
{
value: "test1",
textAlign: "center",
background: "rgb(255,255,255)",
color: "rgb(0,62,117)"
},
{
value: "London",
textAlign: "center",
background: "rgb(255,255,255)",
color: "rgb(0,62,117)"
},
{
value: "120.83",
textAlign: "center",
background: "rgb(255,255,255)",
color: "rgb(0,62,117)"
},
]
},
{
cells:
[
{
value: 2,
textAlign: "center",
background: "rgb(255,255,255)",
color: "rgb(0,62,117)"
},
{
value: "test2",
textAlign: "center",
background: "rgb(255,255,255)",
color: "rgb(0,62,117)"
},
{
value: "shanghai",
textAlign: "center",
background: "rgb(255,255,255)",
color: "rgb(0,62,117)"
},
{
value: "124.83",
textAlign: "center",
background: "rgb(255,255,255)",
color: "rgb(0,62,117)"
},
]
},
我只是无法理解,那一定是星期一的雾!
谢谢
答案 0 :(得分:1)
您可以使用Array.map()
和Object.values()
来做到这一点:
const data = [
{ id : 1, name : "test1", location : "London", cost: "120.83" },
{ id : 2, name : "test2", location : "shanghai", cost: "124.83" },
{ id : 3, name : "test3", location : "Barcelona", cost: "56.54" }
];
const cell = { textAlign: 'center', background: 'rgb(255,255,255)', color: 'rgb(0,62,117)' };
const result = data.map(x =>
({ cells: Object.values(x).map(v => ({ value: `${v}`, ...cell })) })
);
console.log(result);
答案 1 :(得分:0)
let arr = [{id:1,name:"test1",location:"London",cost:"120.83"},{id:2,name:"test2",location:"shanghai",cost:"124.83"},{id:3,name:"test3",location:"Barcelona",cost:"56.54"}]
let defaultObject = {textAlign: "center",background: "rgb(255,255,255)",color: "rgb(0,62,117)" }
let op = arr.map(e => Object.values(e).reduce((op,inp) => {
op.cells.push({value: inp, ...defaultObject } )
return op
},{cells:[]})
)
console.log(op)
答案 2 :(得分:0)
您可以使用.map()
和Object.assign()
方法:
const data = [
{id : 1, name : "test1", location : "London", cost: "120.83"},
{id : 2, name : "test2", location : "shanghai", cost: "124.83"},
{id : 3, name : "test3", location : "Barcelona", cost: "56.54"}
];
const obj = {
textAlign: "center",
background: "rgb(255,255,255)",
color: "rgb(0,62,117)"
};
const result = data.map(o => ({
cells: Object.keys(o).map(k => Object.assign({}, {value: o[k]}, obj))
}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }