How to place a property name on a Javascript object?

Asked

Viewed 239 times

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 name the property, so it wouldn’t 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 accuses error, see: http://jsfiddle.net/61cmd6r3/

Maybe I’m scrambling some concepts (even basic), I expect a light from you so I understand better, I’m very confused..

  • 2

    What exactly do you want to do? Like p2: receives an array, you cannot name...

  • 1

    This is called: Syntax error :)

2 answers

7


This is an object:

{qq: "qq_val"}

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 brackets ([ and ]), and the separation between member objects of the same collection is made with commas, in this way:

[{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, their attempt to name an object occurred directly in the collection:

[prop_name:{ [...]

Collections have no attributes, only a list of objects.

  • 2

    I liked the way you explained it, helped me understand the concepts better.

2

I am seeing that you are trying to assign an attribute to the array as if it were an object by your example.

[prop_name:{ [...]

Perhaps something that can help you, since you are having difficulties, would be seeing how the statement of the object.

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 there’s something wrong.

Example:

js.p1 = {}

js.p2 = {}

js.p2.qq = "valor"

js.p1.qq = 'outro valor';

Then you do the following to see the statement:

JSON.stringify(js)

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

I’d do something like that just to see where I’m going wrong :)

  • Good suggestion, doing this gets more in the face that, what I was doing, was in fact something bizarre, rsrs.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.