IrfanClemson
IrfanClemson

Reputation: 1779

Node.js split JSON Object Per a Value

I have a Node 10+ script that needs to split a JSON object. I have looked for various solutions but none fits my particular needs. Here is my object:

[ 
[ 
  {agent_id: '123',   start: '10-05-2018'},
  { agent_id: '123', start: '10-05-2018'} 
],
[ 
  { agent_id: '456', start: '10-04-2018'},
  { agent_id: '456', start: '10-05-2018'} 
] 
]

So there are two elements/nodes; one has agent_id of '123' and the other has '456'. But what needs to happen is if the start is the same in an element then no need to split, as in the case of agent_id of '123'. But in the case of start being different than that needs to split. So the end result in the case of the above object should be something like below. As you can see, there are three elements to the result. I have a look into 'map' or 'set' or other examples but none apply in my case. And hence I am here.

Thank you!

 [
    [
     { agent_id: '123',   start: '10-05-2018'},
     { agent_id: '123', start: '10-05-2018'}
    ],
    [ { agent_id: '456', start: '10-04-2018'}],
    [ { agent_id: '456', start: '10-05-2018'}]
    ]

Upvotes: 0

Views: 197

Answers (2)

kavigun
kavigun

Reputation: 2365

If you are not using lodash, you can try the following code in vanilla JS:

let input = [
    [
        { agent_id: '123', start: '10-05-2018' },
        { agent_id: '123', start: '10-05-2018' }
    ],
    [
        { agent_id: '456', start: '10-04-2018' },
        { agent_id: '456', start: '10-05-2018' }
    ]
];

function recursiveFunc(arrItem, resultingArr) {
    if (Array.isArray(arrItem) && arrItem.length) {
        let matchArr = []; let restArr = [];
        arrItem.every((v) => {
            if (!(v.start === arrItem[0].start)) {
                restArr.push(v);
            } else {
                matchArr.push(v);
            }
            return v.start === arrItem[0].start;
        });
        if (matchArr.length) resultingArr.push(matchArr);
        if (restArr.length > 1) {
            return recursiveFunc(restArr, resultingArr);
        } else {
            if (restArr.length) resultingArr.push(restArr);
        }
    }
}

let resultingArr = [];
input.forEach(arrItem => {
    recursiveFunc(arrItem, resultingArr);
});
console.log(resultingArr);

Upvotes: 2

Anatoly
Anatoly

Reputation: 22783

Using groupBy method from lodash package:

const _ = require('lodash')

const items = [ 
[ 
  {agent_id: '123',   start: '10-05-2018'},
  { agent_id: '123', start: '10-05-2018'} 
],
[ 
  { agent_id: '456', start: '10-04-2018'},
  { agent_id: '456', start: '10-05-2018'} 
] 
]

const result = items
  .map(x => Object.values(_.groupBy(x, el => `${el.agent_id}:${el.start}`)))
  .reduce((curr, next) => curr.concat(next), [])

Upvotes: 1

Related Questions