0

I would like to know if there is a way to get the length from a nested array.

My data is a JSON file like this:

{
    "data" :[
        "item1" :'',
        "item2" :[{
            "id" :1,
            "text":'text'
        },{
            "id" :2,
            "text" : 'text 
        }] 
    ]
}

I'm using angular 6 and ngx-restangular. Is possible to get the item 2 length?

4
  • 1
    Won’t data.item2.length help? Commented Sep 3, 2018 at 5:36
  • 1
    You are missing a single-quote at the end of text (after id - 2) and you can't give items in arrays names (meaning item1, item2) Commented Sep 3, 2018 at 5:36
  • Is this a valid json? Commented Sep 3, 2018 at 5:37
  • @AnuradhaGunasekara no this is completely invalid Commented Sep 3, 2018 at 5:38

2 Answers 2

4

The main problem is the question does not provide a valid json. A valid json for the same would be like as under :

{
    "data": {
        "item1": "",
        "item2": [{
                "id": 1,
                "text": "text"
            },
            {
                "id": 2,
                "text": "text"
            }
        ]
    }
}

Now you can fetch the second element size simply by

data["item2"].length

or

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

Comments

0

To extend the Answer from @AurA

If you had to work with a valid array:

[
  [ "item0.0", "item0.1" ],
  [ "item1.0", "item1.1" ]
]

you could access the length of the nested arrays like this:

let a = [
  ["item0.0", "item0.1"],
  ["item1.0", "item1.1"]
];

let lengthA0 = a[0].length;
let lengthA1 = a[1].length;

console.log("length of a0: ", lengthA0);
console.log("length of a1: ", lengthA1);

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.