map() 函数返回对象而不是数组

8
抱歉,如果标题有误导性,我不确定如何准确地描述我正在寻找的内容。

I have an array result which I want to turn into multiple objects where each objects property is the field Name Test I need to keep my result.map method as I use it to merge result with data

  result = [{
      "Name Test": "Yellow",
      Count: 124,

    },
    {
      "Name Test": "Black",
      Count: 124,
    },
    {
      "Name Test": "Blue",
      Count: 124,
    }
  ];

  data = [{
      "Name Test": "Yellow",
      pop: 1
    },
    {
      "Name Test": "Black",
      pop: 1
    },
    {
      "Name Test": "Blue",
      pop: 1
    }
  ];


result = result.map((obj1, index) => {
    const obj2 = data[index];
    return {
        [obj1["Name Test"].toUpperCase()]: {
            Count: obj1.Count,
            pop: obj2.pop,
        }
    };
});
console.log(JSON.stringify(result))

这段代码返回一个对象数组,这不是我想要的,因为我需要在我的代码中稍后使用result ["YELLOW"]。 因此,我需要结果以没有数组的这种格式呈现。
{  
   "YELLOW":{  
      "Count":124,
      "pop":1
   },
   "BLACK":{  
      "Count":124,
      "pop":1
   },
   "BLUE":{  
      "Count":124,
      "pop":1
   }
}

我希望这有意义,我感觉离我想要的很近,只是缺少一些小东西,但我尝试让它工作的每种方式都变成了语法错误。

你应该查看 array.reduce - ray
3个回答

9

map()总是返回一个数组。

  • 你应该使用reduce(),并将累加器设置为空对象{}

  • 使用解构和展开语法来隔离Name Test和其他属性。

  • 将键为"Name Test"的每个对象的属性作为累加器的属性,并将其值设置为对象的其余部分。

const arr = [{ "Name Test": "Yellow", Count: 124, pop: 1 }, { "Name Test": "Black", Count: 124, pop: 1 }, { "Name Test": "Blue", Count: 124, pop: 1 } ];

const res = arr.reduce((ac,{["Name Test"]:x,...rest}) => (ac[x] = rest,ac),{})

console.log(res)


4

map会创建一个新的数组。所以你可以使用reduce,并在累加器中传递一个空对象。

let result = [{
    "Name Test": "Yellow",
    Count: 124,
    pop: 1
  },
  {
    "Name Test": "Black",
    Count: 124,
    pop: 1
  },
  {
    "Name Test": "Blue",
    Count: 124,
    pop: 1
  }
];

let newResult = result.reduce(function(acc, curr) {
  // acc is accumulator which is the required object.
  // this will create a nee key in accumulator and will set its value
  acc[curr['Name Test'].toUpperCase()] = {
    Count: curr.Count,
    pop: curr.pop
  }
 return acc;
}, {}) // {} is accumulator object. This will hold the required keys and values

console.log(newResult)


嗨@brk,我一开始没用reduce的原因是我在map函数内合并了2个数组 https://jsfiddle.net/cqraohy5/1/。这就是合并后问题的样子,但是用reduce方法就无法工作。 - DanielJ
1
@DanielJ 的意思是 map 函数永远不会返回对象。 - brk
我已经编辑了我的原始问题,以澄清我正在问@brk的内容,那么在我的情况下,我是否需要使用map进行合并,然后使用reduce方法进行减少? - DanielJ

1

这在微软浏览器中尚不可用(我想),但 fromEntries() 对此非常有用。您可以传递一个可迭代对象或键值对,例如来自 map() 的结果。

let result = [{"Name Test": "Yellow",Count: 124,pop: 1},{"Name Test": "Black",Count: 124,pop: 1},{"Name Test": "Blue",Count: 124,pop: 1}];
let data = [{"Name Test": "Yellow",pop: 1},{"Name Test": "Black",pop: 1},{"Name Test": "Blue",pop: 1}];

let o = Object.fromEntries(result.map(({'Name Test':n, ...o}) => ([n, o])))
let d = Object.fromEntries(result.map(({'Name Test':n, ...o}) => ([n, o])))
 
console.log(Object.assign(o, d))


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接