有沒有辦法使用 map 函式從下面示例中的陣列創建映射(將字串映射到陣列)?不確定如何將物件附加到已經存在的鍵上,而不是覆寫已經存在的鍵
想
{"Germany": [{score: 1}], "Austria": [{score: 1}], "Switzerland": [{score: 2},{score: 3}]}
得到
{"Germany": [{score: 1}], "Austria": [{score: 1}], "Switzerland": [{score: 3}]}
let data = [
{country: 'Germany', score: 1},
{country: 'Austria', score: 1},
{country: 'Switzerland', score: 2},
{country: 'Switzerland', score: 3}
];
let dictionary = Object.assign({}, ...data.map((x) => ({[x.country]: [{score: x.score}]})));
uj5u.com熱心網友回復:
相當簡單reduce(),一些解構和傳播語法:
const data = [
{country: 'Germany', score: 1},
{country: 'Austria', score: 1},
{country: 'Switzerland', score: 2},
{country: 'Switzerland', score: 3}
];
const result = data.reduce((a, {country, score}) => ({
...a,
[country]: [...a[country] || [], {score}]
}), {});
console.log(result);
uj5u.com熱心網友回復:
您可以使用該reduce函式,它接受一個陣列并根據對陣列的每個元素執行的某些操作回傳一個值。
在您的情況下,此操作可能是將分數添加到另一個物件中已經存在的鍵。
該reduce函式接受一個帶有兩個引數的回呼,一個收集器和一個當前專案。
let data = [
{country: 'Germany', score: 1},
{country: 'Austria', score: 1},
{country: 'Switzerland', score: 2},
{country: 'Switzerland', score: 3}
];
// since the reduce function returns a new object, we don't need to deep copy it.
let dictionary = data.reduce((collector, x) => {
// we first have to check if the key exists in the collector object.
// to do so, we use the `in` operator, and negate it's output.
if(!(x.country in collector)) {
collector[x.country] = [];
}
// we, then, can push the current element's score into the appropriate array
collector[x.country].push({score: x.score});
// and we need to return the updated value. In our case, it's the collector.
return collector;
}, {} /** the secon parameter of the function is the initials value of the collector */);
console.log(dictionary)
uj5u.com熱心網友回復:
您可以使用Array.prototype.reduce()來實作它。
嘗試如下:
let data = [
{ country: "Germany", score: 1 },
{ country: "Austria", score: 1 },
{ country: "Switzerland", score: 2 },
{ country: "Switzerland", score: 3 },
];
const output = data.reduce((prev, { country, score }) => {
if (prev[country]) {
prev[country].push({ score });
} else {
prev[country] = [{ score }];
}
return prev;
}, {});
console.log(output);
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/479822.html
標籤:javascript
