0

I'm trying to get data from a nested js object and here is my input.

var data = 
    [ [ { Id: '123', Name: 'Abc', Amount: 110000 } 
      , { Id: '567', Name: 'DEF', Amount:  98000 } 
      , { Id: '345', Name: 'XYZ', Amount: 145000 } 
      ] 
    , [ { Id: '656', Name: 'Abc', Amount: 110000 } 
      , { Id: '223', Name: 'DEF', Amount:  98000 } 
      , { Id: '897', Name: 'XYZ', Amount: 145000 } 
    ] ] 

And here when I want to get data of 223.
I am not much aware of how we can do it in nested js object .
In regular js object array, I use the filter method like below.

var result= data.filter(element => ((element.Id == "223")).

But how Can I do it in case of nested js object (in ES6)?

I referred to post here and made a small fiddle here, which isn't working as expected.

3
  • Id are unique ? if they are, why don'you use find() method ? Commented Oct 7, 2020 at 21:35
  • Nested JSON? You mean an array of arrays with Objects? Commented Oct 7, 2020 at 21:40
  • @epascarello original post was JSON Commented Oct 7, 2020 at 21:42

2 Answers 2

1

I'd just flatten it first (first console log), unless you want the whole "outer" array, in which case just do .find twice:

var data = [
  [{
      "Id": "123",
      "Name": "Abc",
      "Amount": 110000
    },
    {
      "Id": "567",
      "Name": "DEF",
      "Amount": 98000
    },
    {
      "Id": "345",
      "Name": "XYZ",
      "Amount": 145000
    }
  ],
  [{
      "Id": "656",
      "Name": "Abc",
      "Amount": 110000
    },
    {
      "Id": "223",
      "Name": "DEF",
      "Amount": 98000
    },
    {
      "Id": "897",
      "Name": "XYZ",
      "Amount": 145000
    }
  ]
];


var result = data.flat().filter(element => element.Id == "223");
console.log(result);

console.log(data.find(el => el.find(item => item.Id === "223")))

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

Comments

1

you can .flat() the data array the first, then just do a simple filter on it and search for the Id you want; or filter array recursively and then search for the Id you want. snippet below demonstrates the second way

let result = data.map( array =>  
   array.filter( item => item.Id === "223" )
).flat();

var data = 
    [ [ { Id: '123', Name: 'Abc', Amount: 110000 } 
      , { Id: '567', Name: 'DEF', Amount:  98000 } 
      , { Id: '345', Name: 'XYZ', Amount: 145000 } 
      ] 
    , [ { Id: '656', Name: 'Abc', Amount: 110000 } 
      , { Id: '223', Name: 'DEF', Amount:  98000 } 
      , { Id: '897', Name: 'XYZ', Amount: 145000 } 
    ] ];

let result = data.map( array =>  array.filter( item => item.Id === "223" )).flat();


console.log(result);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.