减少时未正确打印数组

我有 1 个 JavaScript 数组。我想根据日期合并这个数组并获取每个价格并将其放入字段中。然而,我只得到的价格是 1。同一日期的其他价格未打印。谁能帮我为什么?谢谢


这是代码:


JavaScript:


var data = [

   {

      "date":"2010-01-01",

      "name":"a"

   },

   {

      "date":"2010-02-01",

      "name":"b"

   },

   {

      "date":"2010-03-01",

      "name":"c"

   },

   {

      "date":"2010-01-01",

      "name":"aa"

   },

   

]


var result1 = data.reduce((p, c) => 

  (p[c.date] = Object.assign({},{name: null}, p[c.date], c)) && p

  , {});


var final = Object.keys(result1).map(x=>result1[x])


console.log(final)

您可以在此处访问代码:


https://jsfiddle.net/q0wn2vuo/


我想要这样的输出:


[{ 日期: "2010-01-01", 名称: 'a,aa', }, { 日期: "2010-02-01", 名称: 'b', }, { 日期: "2010-03-01 “,价格:'c',}]


繁花不似锦
浏览 108回答 2
2回答

九州编程

干得好。var data = [&nbsp; &nbsp;{&nbsp; "date":"2010-01-01",&nbsp; "name":"a"&nbsp; &nbsp;},&nbsp; &nbsp;{&nbsp; "date":"2010-02-01",&nbsp; "name":"b"&nbsp; &nbsp;},&nbsp; &nbsp;{&nbsp; "date":"2010-03-01",&nbsp; "name":"c"&nbsp; &nbsp;},&nbsp; &nbsp;{&nbsp; "date":"2010-01-01",&nbsp; "name":"aa"&nbsp; &nbsp;},&nbsp; &nbsp;]const resultSet = {};&nbsp;for (let i = 0, _len = data.length; i < _len; i++ ) {&nbsp; &nbsp; &nbsp; &nbsp;if(resultSet[data[i].date]){&nbsp; &nbsp; &nbsp; &nbsp; resultSet[data[i].date] += ","+data[i].name&nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp;else{&nbsp; &nbsp; &nbsp; &nbsp; resultSet[data[i].date] = data[i].name&nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; }const resultArr = Object.entries(resultSet).map(([key,value])=>{&nbsp;return { date: key, name: value }})console.log(resultArr)

婷婷同学_

尝试:var data = [&nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; "date":"2010-01-01",&nbsp; &nbsp; &nbsp; "name":"a"&nbsp; &nbsp;},&nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; "date":"2010-02-01",&nbsp; &nbsp; &nbsp; "name":"b"&nbsp; &nbsp;},&nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; "date":"2010-03-01",&nbsp; &nbsp; &nbsp; "name":"c"&nbsp; &nbsp;},&nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; "date":"2010-01-01",&nbsp; &nbsp; &nbsp; "name":"aa"&nbsp; &nbsp;},&nbsp;&nbsp;]var result1 = data.reduce((accum, curr) => {&nbsp; if (!accum[curr.date]) {&nbsp; &nbsp; return {...accum, [curr.date]: [curr.name] }&nbsp; }&nbsp; return {...accum, [curr.date]: [...accum[curr.date], curr.name] }}, {})var final = Object.keys(result1).map(date => ({&nbsp; date: date,&nbsp; name: result1[date].join(',')}))console.log(final)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript