将数组转换为具有数组值的对象

时间:2019-10-28 18:58:16

标签: javascript arrays

我需要变换这个数组

[ { _id: 'indoor', count: 12 }, { _id: 'outdoor', count: 34 } ]

进入此结果:

{ label: ['in', 'out'], data: [12, 34]}

因此,我需要在数组中获取标签(_id),并用一些单独的文本替换它们,并且需要将值作为数据数组获取。 两者的顺序当然应该相同。

对于第二部分,我会做类似的事情

array.map(c => c.count)

我可以对标签值执行相同的操作,但是如何使用单个文本? 例如。 “室内”应替换为“汽车”,“室外”应替换为“飞机”。

6 个答案:

答案 0 :(得分:1)

let labels = {
  indoor: 'car',
  outdoor: 'plaine'
};

let input = [{
  _id: 'indoor',
  count: 12
}, {
  _id: 'outdoor',
  count: 34
}];
let output = input.reduce((output, inObj) => {
  output.label.push(labels[inObj._id]);
  output.data.push(inObj.count);
  return output;
}, {
  label: [],
  data: []
});

console.log(output);

答案 1 :(得分:1)

您可以使用reduce方法:

let sourceData = [
    { _id: 'indoor', count: 12 },
    { _id: 'outdoor', count: 34 }
];

const maps = {indoor: 'in', outdoor: 'out'};    

const result = sourceData.reduce((a, c) => {
    a.label = a.label || [];
    a.data = a.data || [];

    a.label.push(maps[c._id]);
    a.data.push(c.count);

    return a;
}, {});

console.log(result);

您可以按自定义顺序对所需的数组进行排序:

let sourceData = [
    { _id: 'indoor', count: 12 },
    { _id: 'outdoor', count: 34 }
];

const maps = {indoor: 'in', outdoor: 'out'};    

const result = sourceData.reduce((a, c) => {
    a.label = a.label || [];
    a.data = a.data || [];

    a.label.push(maps[c._id]);
    a.data.push(c.count);

    return a;
}, {});

result.label.sort((a, b) => {
  const order = {'out': 1, 'in': 2, undefined: 3};
  return order[a] - order[b];
});

console.log(`custom order of labels: `, result);

答案 2 :(得分:1)

const data = 
[ 
  { _id: 'indoor', count: 12 }, 
  { _id: 'outdoor', count: 34 } 
]
const result = {
  label: data.map(a => a._id.replace('door','')),
  data: data.map(e => e.count)
}

console.log(result)

答案 3 :(得分:0)

在地图回叫中,您可以检查文本并返回所需的字符串

let data = [{
  _id: 'indoor',
  count: 12
}, {
  _id: 'outdoor',
  count: 34
}]

let newData = {
  label: data.map((item) => {
    if (item._id === 'indoor') {
      return 'in';
    } else {
      return 'out';
    }

  }),
  data: data.map(item => item.count)

};
console.log(newData)

答案 4 :(得分:0)

const arr = [ { _id: 'indoor', count: 12 }, { _id: 'outdoor', count: 34 } ];   
arr.map(o => [o._id === 'indoor' ? 'in' : 'out', o.count])
    .reduce((p, c) => ({
        label: [...p.label, c[0]]),
        data: [...p.data, c[1]])
    }), {
        label: [],
        data: []
    })

答案 5 :(得分:0)

const data = [ { _id: 'indoor', count: 12 }, { _id: 'outdoor', count: 34 } ];

const indoor = data.filter((item) => item._id === 'indoor').map((i) => i.count);
const outdoor = data.filter((item) => item._id === 'outdoor').map((i) => i.count);

const res = { label: ['in', 'out'], data: [...indoor, ...outdoor]};

console.log(res);

接下来会给你

{
  label: [
    "in",
    "out"
  ],
  data: [
    12,
    34
  ]
}