How do I put a property name in a JavaScript Object?

3
    js = {
        p1: {
            qq: "qq_val",
        },
        p2: [{
            qq: "qq_val",
        }]
    };


    json = JSON.stringify(js);
    console.log(json); // {"p1":{"qq":"qq_val"},"p2":[{"qq":"qq_val"}]}

Well, I just wanted to give the property a name, so it would not be empty, I tried something like:

js = {
    p1: {
        qq: "qq_val",
    },
    p2: [prop_name:{ // aqui eu coloco o nome da propriedade.
        qq: "qq_val",
    }]
};


json = JSON.stringify(js);
console.log(json); // {"p1":{"qq":"qq_val"},"p2":[{"qq":"qq_val"}]}

But you acknowledge the error, see: link

Maybe I'm shuffling some concepts (even if basic), I hope a light of you to understand better, I'm very confused ..

    
asked by anonymous 12.09.2015 / 17:56

2 answers

7

This is an object:

{qq: "qq_val"}

It has an attribute, qq , whose value is the string qq_val . The notation is correct.

This is a collection with a single member:

[{qq:"qq_val"}]

A collection is determined by the brackets ( [ and ] ), and the separation between member objects of the same collection is done with commas, like this:

[{a:1}, {b:2}, {c:3},(...)]

This is an object, which has an attribute called p2 , whose value is a collection:

{p2:[{qq:"qq_val"}]}

All these objects are well formed. However, your attempt to name an object occurred directly in the collection:

[prop_name:{ [...]

Collections have no attributes, just a list of objects.

    
12.09.2015 / 18:10
2

I'm seeing that you're trying to assign an attribute to the array as if it were an object by its example.

[prop_name:{ [...]

Maybe something that can help you, since you are having difficulties, would see how the object declaration is given.

First mount it line by line, and then see what the statement would look like. So you can compare it to your object and see if something is wrong.

Example:

js.p1 = {}

js.p2 = {}

js.p2.qq = "valor"

js.p1.qq = 'outro valor';

Then you'll do the following to see the statement:

JSON.stringify(js)

{"p1":{"qq":"outro valor"},"p2":{"qq":"valor"}}

I would do something like this just to see where I'm going wrong:)

    
12.09.2015 / 18:17