简体   繁体   中英

Group and Sort objects in array Javascript

I have an input like this:

var input = [{IdDevice:"1", Time: '11:01:00', Data: '1,2,3' }, 
             {IdDevice:"2", Time: '11:01:11', Data: '4,5,6' },
             {IdDevice:"1", Time: '11:02:00', Data: 'a,b,c' }, 
             {IdDevice:"2", Time: '11:02:11', Data: 'x,y,z' }]

After process 1:

var output1 = input.map(a => a.Data.split(','))[0].map((_, idx) => {return {data: input.map(a => a.Data.split(',')[idx])}});
console.log(output1)

I have output1:

[
  { data: [ '1', '4', 'a', 'x' ] },
  { data: [ '2', '5', 'b', 'y' ] },
  { data: [ '3', '6', 'c', 'z' ] }
]

After process 2:

output1.forEach((each, index) => each.name = `item ${index + 1}`);
console.log(output1)

I have output:

[
  { data: [ '1', '4', 'a', 'x' ], name: 'item 1' },
  { data: [ '2', '5', 'b', 'y' ], name: 'item 2' },
  { data: [ '3', '6', 'c', 'z' ], name: 'item 3' }
]

And now I want output also depend "IdDevice" like this:

[
  { data: [ '1', 'a'], name: 'device 1 item 1' },
  { data: [ '2', 'b'], name: 'device 1 item 2' },
  { data: [ '3', 'c'], name: 'device 1 item 3' },
  { data: [ '4', 'x'], name: 'device 2 item 1' },
  { data: [ '5', 'y'], name: 'device 2 item 2' },
  { data: [ '6', 'z'], name: 'device 2 item 3' }
]

And a sub question, when I type:

var output2 = output1.forEach((each, index) => each.name = `item ${index + 1}`);
console.log(output2)

The output2 will be undefined. Thanks for advanced.

I would gather the device ids at the first stage, and carry them through some transformations, with code like this:

 const convert = (input) => Object.entries (input.flatMap ( ({IdDevice, Data}) => Data.split (',').map ( (x, i) => ({data: x, name: `device ${IdDevice} item ${i + 1}`}) ) ).reduce ( (a, {data, name}) => ((a [name] = a[name] || []), (a[name].push(data)), a), {} )).map ( ([name, data]) => ({data, name}) ) var input = [{IdDevice:"1", Time: '11:01:00', Data: '1,2,3' }, {IdDevice:"2", Time: '11:01:11', Data: '4,5,6' }, {IdDevice:"1", Time: '11:02:00', Data: 'a,b,c' }, {IdDevice:"2", Time: '11:02:11', Data: 'x,y,z' }] console.log (convert (input))
 .as-console-wrapper {max-height: 100%;important: top: 0}

This goes through several stages. After the flatMap call, we get

[
  {"data": "1", "name": "device 1 item 1"}, 
  {"data": "2", "name": "device 1 item 2"}, 
  // ...
  {"data": "z", "name": "device 2 item 3"}
]

Then after reduce , we have this:

{
  "device 1 item 1": ["1", "a"], 
  "device 1 item 2": ["2", "b"],
  // ...
  "device 2 item 3": ["6", "z"]
}

Object.entries slightly restructures this to:

[
  ["device 1 item 1", ["1", "a"]], 
  ["device 1 item 2", ["2", "b"]], 
  // ...
  ["device 2 item 3", ["6", "z"]]
]

And finally, map changes it to your requested output format:

[
  {"data": ["1", "a"], "name": "device 1 item 1"}, 
  {"data": ["2", "b"], "name": "device 1 item 2"}, 
  // ...
  {"data": ["6", "z"], "name": "device 2 item 3"}
]

While some of these steps could certainly be consolidated, I find it easier to work this way, and would keep it unless some evidence proved that this was an actual hotspot in my application.

 let input = [ { IdDevice: "1", Time: "11:01:00", Data: "1,2,3" }, { IdDevice: "2", Time: "11:01:11", Data: "4,5,6" }, { IdDevice: "1", Time: "11:02:00", Data: "a,b,c" }, { IdDevice: "2", Time: "11:02:11", Data: "x,y,z" }, ]; const getDeviceArrayMap = input.reduce((deviceArrayMap, device) => { if (deviceArrayMap[device.IdDevice]) { deviceArrayMap[device.IdDevice] = [...deviceArrayMap[device.IdDevice], ...device.Data.split(","), ]; } else { deviceArrayMap[device.IdDevice] = [...device.Data.split(",")]; } return deviceArrayMap; }, {}); const getOutput = Object.keys(getDeviceArrayMap).reduce( (outputArray, deviceId) => { for (let i = 0; i < getDeviceArrayMap[deviceId].length / 2; i++) { outputArray.push({ data: [ getDeviceArrayMap[deviceId][i], getDeviceArrayMap[deviceId][i + 3], ], name: `device ${deviceId} item ${i + 1}`, }); } return outputArray; }, [] ); console.log(getOutput)

You can use map to get the desired result.

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

 var input = [ { IdDevice: "1", Time: "11:01:00", Data: "1,2,3" }, { IdDevice: "2", Time: "11:01:11", Data: "4,5,6" }, { IdDevice: "1", Time: "11:02:00", Data: "a,b,c" }, { IdDevice: "2", Time: "11:02:11", Data: "x,y,z" }, ]; var output1 = input.map((a) => a.Data.split(","))[0].map((_, idx) => { return { data: input.map((a) => a.Data.split(",")[idx]) }; }); const output2 = output1.map((each, index) => ({ data: each.data, name: `item ${index + 1}`, })); console.log(output2);

const input = [
    { IdDevice: '1', Time: '11:01:00', Data: '1,2,3' },
    { IdDevice: '2', Time: '11:01:11', Data: '4,5,6' },
    { IdDevice: '1', Time: '11:02:00', Data: 'a,b,c' },
    { IdDevice: '2', Time: '11:02:11', Data: 'x,y,z' },
];

const output1 = input
    .map(val => val.Data.split(','))[0]
    .map((val, i) => {
        return {
            data: input.map(diff => {
                return diff.Data.split(',')[i];
            }),
        };
    });

console.log(output1);
const output2 = output1.map((val, i) => {
    val.name = `item ${i + 1}`;
    return val;
});
console.log(output2);

const final_output = [];
let temp_index = 0;
let alphabet = 2;
let num = 0;
for (let i = 0; i < output2.length * 2; i++) {
    const new_data = { data: [], name: '' };
    if (temp_index >= output2.length) {
        temp_index = 0;
        alphabet++;
        num++;
    }
    new_data.data.push(`${i + 1}`);
    new_data.data.push(output2[temp_index].data[alphabet]);
    new_data.name = `device ${num + 1} ` + output2[temp_index].name;
    final_output.push(new_data);
    temp_index++;
}
console.log(final_output);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM