0

Basically, I have the following array (or JSON):

apps = {
    app1:
    [
        "ci-extension",
        "Unnamed",
        "<h1>Hello world!</h1>"
    ],
    app2:
    [
        "ci-extension",
        "Another one!",
        "Cool!"
    ],
}

Is there any way to determine how many children does the array have? E.g. in this case the answer is 2: app1 & app2. And if we add one more object "application" the answer will be 3. I tried the following:

apps.length
//returns "undefined"

for (i = 0; apps[i] != undefined; i++) {
    console.log(apps[i]);
    //also returns "undefined"
    //I am later gonna use also the values in the child, so I stored all the children to a new array
    meta.push(apps[i]); //"meta" here is another vriable with an array in it
}

(if this makes any sense)
I expected the for to return something like this:

app1
app2
application (if you count the new object we added)

And the value of meta to be ["app1", "app2", "application"].

My mind got totally obfuscated. I've got no idea where and what I am doing wrong, so any help would be highly appreciated. Thanks in advance!

EDIT: If there is some way to push() elements into apps I will kindly ask you to light me up. Thanks again!

Mona Lisa
  • 193
  • 1
  • 10
  • 3
    `apps` is not an array, nor is it JSON - it's an [object literal](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Object_literals). – chazsolo Sep 20 '17 at 15:09

1 Answers1

0

You can do the following

let apps = {
    app1:
    [
        "ci-extension",
        "Unnamed",
        "<h1>Hello world!</h1>"
    ],
    app2:
    [
        "ci-extension",
        "Another one!",
        "Cool!"
    ],
}

let result = Object.keys(apps).length;

console.log(result);
here Object.keys() would return an array of all keys in the object. You simply need the length of this array which would give you the total number of keys in the object

You can assign properties to this object in the following way

let apps = {
    app1:
    [
        "ci-extension",
        "Unnamed",
        "<h1>Hello world!</h1>"
    ],
    app2:
    [
        "ci-extension",
        "Another one!",
        "Cool!"
    ],
}

apps['app3'] = ["test"];
let result = Object.keys(apps).length;
console.log(result);
// or the following way
let objectToPush = {app4: ['test2']};
Object.assign(apps, objectToPush);
console.log(Object.keys(apps));
console.log(Object.keys(apps).length);
marvel308
  • 9,593
  • 1
  • 16
  • 31