0

I have an jason result as below and I want to read from it and push to specific key as below JSON result

[
{id:1,Name:"test",billNumber:"123"}
{id:2,Name:"test1",billNumber:"123"}
{id:3,Name:"test2",billNumber:"12345"}
{id:2,Name:"test3",billNumber:"12345"}
{id:3,Name:"test4",billNumber:"12334535"}
]

I want to have array list as below

{
"123":[{id:1,Name:"test",billNumber:"123"}, {id:2,Name:"test1",billNumber:"123"}],
"12345":[ {id:3,Name:"test2",billNumber:"12345"},{id:2,Name:"test3",billNumber:"12345"}],
"12334535":[{id:3,Name:"test4",billNumber:"12334535"}]
}

How to get the above list from the json result. Please do help

4 Answers 4

2

You don't need lodash to do that: just a regular Array.prototype.reduce will do the work. At each iteration, you simply check if the billNumber of the current item is in the object:

  • if it is not (i.e. a new entry), then you assign an array with a single element
  • if it is (i.e. the billNumber has been encountered before), then you simply push into the array

See proof-of-concept below:

const data = [{
  id: 1,
  Name: "test",
  billNumber: "123"
}, {
  id: 2,
  Name: "test1",
  billNumber: "123"
}, {
  id: 3,
  Name: "test2",
  billNumber: "12345"
}, {
  id: 2,
  Name: "test3",
  billNumber: "12345"
}, {
  id: 3,
  Name: "test4",
  billNumber: "12334535"
}];

const transformedData = data.reduce((acc, cur) => {
  if (cur.billNumber in acc) {
    acc[cur.billNumber].push(cur);
  } else {
    acc[cur.billNumber] = [cur];
  }

  return acc;
}, {});
console.log(transformedData);

Sign up to request clarification or add additional context in comments.

Comments

1

Use groupBy from lodash: const result = groupBy(input, "billNumber") (input is your array)

Comments

1

you can use reduce method.

[
{id:1,Name:"test",billNumber:"123"},
{id:2,Name:"test1",billNumber:"123"},
{id:3,Name:"test2",billNumber:"12345"},
{id:2,Name:"test3",billNumber:"12345"},
{id:3,Name:"test4",billNumber:"12334535"},
].reduce((acc, value) => {
    if (!acc[value.billNumber]) {
        acc[value.billNumber] = [];
    }
    
    acc[value.billNumber].push(value);
    return acc;
}, {})

Comments

-1

Here is the mimic code You cann use and get help

var a = [{a:2},{a:3},{a:4}]

let b = {}
let c = 1
a.forEach(obj => {
  b[c] = [obj]
  c++
})

output will be

{ 
  1: [ { a: 2 } ],
  2: [ { a: 3 } ], 
  3: [ { a: 4 } ] 
}

Thanks I hope it will help !

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.