jquery JavaScript数组,如果一个元素相同,则需要数组中的另一个元素

kmbjn2e3  于 2023-06-29  发布在  jQuery
关注(0)|答案(2)|浏览(160)

我想把一个数组转换成新的格式
这是我的数组

let data = [
 { operatorName: 'MBC', negativeTotal: -5873, postiveTotal: 15632 },
 { operatorName: 'OSEN+', negativeTotal: -4071, postiveTotal: 2206 }
];

这里我想把data转换成这种格式
预期阵列结果:

[
    {
        data : [2206, -4071],
        label:'OSEN+'
    },
    {
        data : [15632,-5873],
        label:'MBC'
    }
];

我试了这个代码:

const uniqueOperators = [...new Set(data.map((x) => x.operatorName))];
let d = []
let dataset = uniqueOperators.map((uniqueOperator) => {
  
  data.find((item)=>{
    if(item.operatorName === uniqueOperator){
      console.log(item)
    }
    
  })
});

但它并没有达到我预期的数组结果。

zvms9eto

zvms9eto1#

这样也行。与@Mamun的答案相同,解构了项目:

let data = [
  { operatorName: "MBC", negativeTotal: -5873, postiveTotal: 15632 },
  { operatorName: "OSEN+", negativeTotal: -4071, postiveTotal: 2206 },
];

const output = data.map(({ operatorName, negativeTotal, postiveTotal }) => ({
  data: [postiveTotal, negativeTotal],
  label: operatorName,
}));

console.log(output);
u7up0aaq

u7up0aaq2#

let data = [{
    operatorName: 'MBC',
    negativeTotal: -5873,
    postiveTotal: 15632
  },
  {
    operatorName: 'OSEN+',
    negativeTotal: -4071,
    postiveTotal: 2206
  }
];
let output = data.map((e) => {
  let obj = {
    data: [e.postiveTotal, e.negativeTotal],
    label: e.operatorName
  }
  return obj;
})

console.log(output);

相关问题