オブジェクトの配列を繰り返し、JavaScriptで新しいオブジェクトを作成するにはどうすればよいですか?
このようなオブジェクトの配列があるとします-
const arr = [
{
"customer": "Customer 1",
"project": "1"
},
{
"customer": "Customer 2",
"project": "2"
},
{
"customer": "Customer 2",
"project": "3"
}
] そのような配列を1つ受け取り、新しい配列を生成(返す)するJavaScript関数を作成する必要があります。
新しい配列では、同じ値を持つすべての顧客キーがマージされ、出力は次のようになります-
const output = [
{
"Customer 1": {
"projects": "1"
}
},
{
"Customer 2": {
"projects": [
"2",
"3"
]
}
}
]> 例
コードを書いてみましょう-
const arr = [
{
"customer": "Customer 1",
"project": "1"
},
{
"customer": "Customer 2",
"project": "2"
},
{
"customer": "Customer 2",
"project": "3"
}
]
const groupCustomer = data => {
const res = [];
data.forEach(el => {
let customer = res.filter(custom => {
return el.customer === custom.customer;
})[0];
if(customer){
customer.projects.push(el.project);
}else{
res.push({ customer: el.customer, projects: [el.project] });
};
});
return res;
};
console.log(groupCustomer(arr)); 出力
そして、コンソールの出力は-
になります[
{ customer: 'Customer 1', projects: [ '1' ] },
{ customer: 'Customer 2', projects: [ '2', '3' ] }
] -
JavaScriptでIDごとにオブジェクトの配列をグループ化する方法は?
以下は、JavaScriptでオブジェクトの配列をIDでグループ化するコードです- 例 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style>
-
JavaScriptでオブジェクトを含む配列の配列をループするにはどうすればよいですか?
以下は、JavaScriptのオブジェクトを含む配列の配列をループするコードです- 例 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style>