大家好,我想做一些“簡單”的事情,但不是為了我,我有這個陣列
[
{ x: 'bmw', vehicule_type: car, y: 1 },
{ x: 'mercedes', vehicule_type: car, y: 2 },
{ x: 'airbus', vehicule_type: plane, y: 1 }
]
我想把它變成這個東西
[
car : [{ x: 'bmw', y: 1 }, { x: 'mercedes', y: 1 }]
plane: [{ x: 'airbus', y: 1 }]
]
我找不到辦法,我看到我可以使用“reducer()”但其余的我迷路了
uj5u.com熱心網友回復:
您可以vehicle_type使用Array.prototype.reduce對資料進行分組。
const
data = [
{ x: "bmw", vehicle_type: "car", y: 1 },
{ x: "mercedes", vehicle_type: "car", y: 2 },
{ x: "airbus", vehicle_type: "plane", y: 1 },
],
result = data.reduce(
(r, { vehicle_type: t, ...o }) => ((r[t] ??= []).push(o), r),
{}
);
console.log(result);
如果您發現難以理解上述解決方案,請參閱這個更具描述性的版本:
顯示代碼片段
const
data = [
{ x: "bmw", vehicle_type: "car", y: 1 },
{ x: "mercedes", vehicle_type: "car", y: 2 },
{ x: "airbus", vehicle_type: "plane", y: 1 },
],
result = data.reduce((r, { vehicle_type: t, ...o }) => {
if (!r[t]) {
r[t] = [];
}
r[t].push(o);
return r;
}, {});
console.log(result);
相關檔案:
- 空值合并運算子 (??)
- 休息引數
- 物件解構
- 逗號運算子 (,)
uj5u.com熱心網友回復:
下面介紹的是實作預期目標的一種可能方式。
代碼片段
const myTransform = arr => (
arr.reduce(
(acc, {vehicule_type, ...rest}) => (
(acc[vehicule_type] ??= []).push({...rest}),
acc
),
{}
)
);
/* EXPLANATION of the code
// method to transform the array
const myTransform = arr => (
arr.reduce( // iterate using ".reduce()" with "acc" as accumulator
// destructure the iterator to acces "vehicule_type"
(acc, {vehicule_type, ...rest}) => (
// if "acc" doesn't have "vehicule_type", set it as empty array
// and then, push "rest" (ie, x, y, other props, if any) into the array
(acc[vehicule_type] ??= []).push({...rest}),
// implicit return of "acc"
acc
),
{} // initialize "acc" as an empty object
)
);
*/
const dataArr = [
{ x: 'bmw', vehicule_type: 'car', y: 1 },
{ x: 'mercedes', vehicule_type: 'car', y: 2 },
{ x: 'airbus', vehicule_type: 'plane', y: 1 }
];
console.log(myTransform(dataArr));
.as-console-wrapper { max-height: 100% !important; top: 0 }
解釋
添加到上述代碼段的行內注釋。
編輯
正如Bergi在下面的評論中所指出的,使用回圈的替代方法for也是可能的。這可能看起來如下所示:
const myTransform = arr => {
const res = {};
for (const {vehicule_type, ...rest} of dataArr) {
(res[vehicule_type] ??= []).push({...rest});
};
return res;
};
/* EXPLANATION
// alternative method to transform the array
const myTransform = arr => {
// set up result "res" as an empty object "{}"
const res = {};
// iterate over elts of "dataArr"
// destructure the iterator to directly access "vehicule_type"
for (const {vehicule_type, ...rest} of dataArr) {
// if "vehicule_type" not already in "res",
// then, set it with a value of empty array
// push the remaining props "...rest" into the array
(res[vehicule_type] ??= []).push({...rest});
};
// return the result
return res;
};
*/
const dataArr = [
{ x: 'bmw', vehicule_type: 'car', y: 1 },
{ x: 'mercedes', vehicule_type: 'car', y: 2 },
{ x: 'airbus', vehicule_type: 'plane', y: 1 }
];
console.log(myTransform(dataArr));
.as-console-wrapper { max-height: 100% !important; top: 0 }
uj5u.com熱心網友回復:
也許快進做這樣的事情是使用Array#forEach助手,在每次迭代中,您只需要檢查是否vehicule_type存在具有相同鍵的物件鍵(您可以簡單地通過使用來做到這一點Array#some)。如果它確實將新結果推送到現有結果,并且如果它沒有創建一個以新元素作為其值的新物件鍵。
所以它會是這樣的:
const array = [{
x: 'bmw',
vehicule_type: 'car',
y: 1
},
{
x: 'mercedes',
vehicule_type: 'car',
y: 2
},
{
x: 'airbus',
vehicule_type: 'plane',
y: 1
}
]
const resultArray = []
array.forEach((arr) => {
if (resultArray.some((resArr) => Object.keys(resArr).includes(arr.vehicule_type))) {
const newObj = resultArray.find((resArr) => Object.keys(resArr).includes(arr.vehicule_type))
const {
vehicule_type,
...rest
} = arr
newObj[arr.vehicule_type] = [...newObj[arr.vehicule_type], rest]
} else {
const obj = {}
const {
vehicule_type,
...rest
} = arr
obj[arr.vehicule_type] = [rest]
resultArray.push(obj)
}
})
console.log(resultArray)
uj5u.com熱心網友回復:
我不確定這是否是最好的方法;可能不是,但這就是我想出的..
let array = [{
x: 'bmw',
vehicle_type: "car",
y: 1
},
{
x: 'mercedes',
vehicle_type: "car",
y: 2
},
{
x: 'airbus',
vehicle_type: 'plane',
y: 1
},
{
x: 'mercedes',
vehicle_type: "car",
y: 2
}
]
function sortByType(array) {
const vehicles = {};
for (let object of array) {
let vehicle = {},
type = undefined;
for (let property in object) {
if (type === undefined) type = object["vehicle_type"];
if (vehicles[type] === undefined) vehicles[type] = [];
if (property === "vehicle_type") continue;
vehicle[property] = object[property];
}
vehicles[type].push(vehicle);
}
return vehicles
}
const vehicles = sortByType(array)
console.log(vehicles)
uj5u.com熱心網友回復:
您可以將Array.prototype.reduce()與Destructuring assignment結合使用
代碼:
const data = [{ x: 'bmw', vehicle_type: 'car', y: 1 },{ x: 'mercedes', vehicle_type: 'car', y: 2 },{ x: 'airbus', vehicle_type: 'plane', y: 1 },]
const result = data.reduce(
(a, { vehicle_type: v, ...c }) => ((a[v] = [...(a[v] || []), c]), a),
{}
)
console.log(result)
uj5u.com熱心網友回復:
使用它,過濾資料后,您可以將主題合并到其他陣列中
讓資料 = [
{ x:'bmw',vehicule_type:“汽車”,y:1 },
{ x:“梅賽德斯”,vehicule_type:“汽車”,y:2 },
{ x:“空中客車”,vehicule_type:“飛機”,y:1 }
]
讓 res = []
const unique = [...new Set(data.map(item => item.vehicule_type))];
unique.forEach((元素)=>{
var vehicule_type = [{[element] : JSON.stringify(data.filter((type)=>type.vehicule_type == element)) }]
res.push(vehicule_type)
})
控制臺.log(res)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/484844.html
標籤:javascript 数组
上一篇:如何安裝反應導航?
