我有以下陣列:
const test = [{
a: 1,
b: 2,
c: 3,
d: 4,
e: 5,
f: 6,
}]
我想要這個
const test = [{a: 1, b: 2, c:3},{d: 4, e:5, f:6}]
uj5u.com熱心網友回復:
你的例子
在這種特殊情況下,您可以這樣做。
const input = [{
a: 1,
b: 2,
c: 3,
d: 4,
e: 5,
f: 6,
}]
const { a, b, c, d, e, f } = input[0];
const output = [
{ a: a, b: b, c: c },
{ d: d, e: e, f: f }
]
console.log(input)
console.log(output)
預期產出
[ { a: 1, b: 2, c: 3, d: 4, e: 5, f: 6 } ]
[ { a: 1, b: 2, c: 3 }, { d: 4, e: 5, f: 6 } ]
一般情況
通過迭代物件屬性,您還可以基于某種條件為具有該形狀的所有輸入實作這種轉換。
const input = [{
a: 1,
b: 2,
c: 3,
d: 4,
e: 5,
f: 6,
}]
const output = []
input.forEach(elem => {
// get entries of object which contains keys and values of the JavaScript object
const entries = Object.entries(elem);
let curObj = {};
entries.forEach((entry, index) => {
curObj[entry[0]] = entry[1]
// some condition on when to create a new object (e.g. every 3rd property)
if((index 1) % 3 === 0){
output.push(curObj);
curObj = {}
}
})
// in case there are some properties left
if(Object.keys(curObj).length !== 0){
output.push(curObj);
}
})
console.log("Input")
console.log(input);
console.log("Output")
console.log(output);
這將為您提供與以前完全相同的結果,但它將適用于物件內的任意數量的屬性以及輸入陣列中的任意數量的物件。
以這個為例input:
const input = [
{
a: 1,
b: 2,
c: 3,
d: 4,
e: 5,
f: 6,
g: 34,
h: 23,
i: 234,
j: 324,
k: 3434,
l: 343,
},
{
a: 1,
b: 2,
c: 3,
d: 4,
e: 5,
f: 6,
g: 34,
h: 23,
i: 234,
j: 324,
k: 3434,
l: 343,
},
];
It will result in this output:
Input
[
{
a: 1,
b: 2,
c: 3,
d: 4,
e: 5,
f: 6,
g: 34,
h: 23,
i: 234,
j: 324,
k: 3434,
l: 343
},
{
a: 1,
b: 2,
c: 3,
d: 4,
e: 5,
f: 6,
g: 34,
h: 23,
i: 234,
j: 324,
k: 3434,
l: 343
}
]
Output
[
{ a: 1, b: 2, c: 3 },
{ d: 4, e: 5, f: 6 },
{ g: 34, h: 23, i: 234 },
{ j: 324, k: 3434, l: 343 },
{ a: 1, b: 2, c: 3 },
{ d: 4, e: 5, f: 6 },
{ g: 34, h: 23, i: 234 },
{ j: 324, k: 3434, l: 343 }
]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/444840.html
上一篇:指向char型別陣列的指標可以不用解參考運算子來顯示陣列的內容嗎?
下一篇:如何將1d陣列的值復制到2d?
