比较 Javascript 中的对象数组

Compare Array of Objects in Javascript

我想制作这个数组:

[
   {main: "material", value: "blend"}, 
   {main: "material", value: "synthetic"}, 
   {main: "style", value: "curl"}, 
   {main: "style", value: "bob"}, 
   {main: "material", value: "premium"}
]

对此:

{
 material: ["blend", "synthetic", "premium"], 
 style: ["curl", "bob"]
}

我使用了两个“for-loops”,但效果不佳:( Javascript

相当新手

您可以使用 reduce 得到该结果

const data = [{
  main: "material",
  value: "blend"
}, {
  main: "material",
  value: "synthetic"
}, {
  main: "style",
  value: "curl"
}, {
  main: "style",
  value: "bob"
}, {
  main: "material",
  value: "premium"
}]

const finalResut = data.reduce((result, currentData) => {
  const {
    main,
    value
  } = currentData
  if (!result[main]) {
    result[main] = []
  }
  result[main].push(value)
  return result
}, {})

console.log(finalResut)
.as-console-wrapper {
  max-height: 100% !important;
  top: 0;
}

使用 For 循环 以下是具体操作方法。您还可以使用@Nick Vu 建议的reduce 函数。

var array = [
   {main: "material", value: "blend"}, 
   {main: "material", value: "synthetic"}, 
   {main: "style", value: "curl"}, 
   {main: "style", value: "bob"}, 
   {main: "material", value: "premium"}
]
var newArray = {material:[],style:[]}
for (var i =0;i<array.length;i++){
    if (array[i].main == "material")
    {newArray.material.push(array[i].value)}
    else
    {newArray.style.push(array[i].value)}}
console.log(newArray)