【问题标题】:Object data Separate Uniqe wise Value in Javascruipt对象数据在Javascript中分离唯一明智的值
【发布时间】:2020-09-15 13:45:02
【问题描述】:

我有对象列表数据。 我必须按值对唯一标识进行明智的排序。以及它们的数据存储各自的唯一标识对象。 ** 对象列表 **

{
 uniqueid : 200,
 name : "sandesh",
 loop: 222,
 salary : 2500
},
{
 uniqueid : 300,
 name : "hello",
 loop: 222,
 salary : 2500
},
{
 uniqueid : 300,
 name : "hello1",
 loop: 222,
 salary : 2500
};

我将明智地创建一个对象 uniqueid 并在那里存储值,但每个数据都会创建重复的对象。

var newArray = [];
    this.userBetHistory.forEach(item => {
       var newItem = {uniqueid : item.uniqueid, BetData: []};
       this.userBetHistory.forEach(innerItem => {
          if(innerItem.uniqueid== item.uniqueid){           
              newItem.BetData = newItem.BetData.concat(innerItem);
          }
       });
      newArray.push(newItem);
    });

** 预期输出:**

{
 uniqueid : 200,
 data : 
     {
      uniqueid : 200,
      name : "sandesh",
      loop: 222,
      salary : 2500
     }
},
{
 uniqueid : 300,
 data : 
      {
        uniqueid : 300,
        name : "hello",
        loop: 222,
        salary : 2500
      },
      {
        uniqueid : 300,
        name : "hello1",
        loop: 222,
        salary : 2500
      }
}

【问题讨论】:

  • 预期输出不是有效的 JSON。

标签: javascript arrays object filter


【解决方案1】:

您可以使用Array.reduce 来格式化数据

let data = [{uniqueid:200,name:'sandesh',loop:222,salary:2500,},{uniqueid:300,name:'hello',loop:222,salary:2500,},{uniqueid:300,name:'hello1',loop:222,salary:2500,},]

const formattedData = (data) => {
  const result = data.reduce((res, d) => {
    if(res[d.uniqueid]) {
      res[d.uniqueid].data.push(d);
    } else {
      res[d.uniqueid] = {
        uniqueid: d.uniqueid,
        data: [
          {...d}
        ]
      }
    }
    return res;
  }, {}) ;
  return Object.values(result);
}

console.log(formattedData(data))

希望这是您正在寻找的输出

【讨论】:

  • 使用此解决方案。谢谢@Nithish
  • 很高兴帮助你@SandeshMankar。
【解决方案2】:

您可以通过一些映射和过滤来做到这一点。

const userBetHistory = [{uniqueid: 200,name: "sandesh",loop: 222,salary: 2500,},{uniqueid: 300,name: "hello",loop: 222,salary: 2500,},{uniqueid: 300,name: "hello1",loop: 222,salary: 2500, }];

let tempData = userBetHistory.map((activeBet) => {
  const activeBetSubData = userBetHistory.filter(
    (bet) => bet.uniqueid === activeBet.uniqueid
  );
  return {
    uniqueid: activeBetSubData[0].uniqueid,
    data: activeBetSubData,
  };
});

tempData = tempData
  .map((item) => item.uniqueid)
  .map((item, i, final) => final.indexOf(item) === i && i)
  .filter((item) => tempData[item])
  .map((item) => tempData[item]);

console.log(tempData);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多