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

时间:2019-05-18 04:26:59

标签: javascript

很抱歉,如果标题误导了我,我不确定如何准确地描述我要寻找的东西。

我有一个数组result,我想将其转换成多个对象,其中每个对象属性是字段Name Test,在合并{{1 }}与result

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"]

我希望这是有道理的,并且我感觉自己很接近我想要的东西,只是缺少了一些小东西,但是我试图使这项工作通过的所有方式都变成了语法错误。

3 个答案:

答案 0 :(得分:2)

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)

答案 1 :(得分:1)

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)

答案 2 :(得分:1)

(我认为)它在MS浏览器中尚不可用,但是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))