简体   繁体   中英

Javascript objects with JSON

Im sure this must have been asked before but I can't find an example on SO. I have a JSON string that starts out life as something like this:

{"model":"14","imgsize":"890","selection":{"SC":"BC","PC":"AC"},"changed":{"PC":"AC"}}

The string needs to be changed on user input such that "selection" records all the input the user has click on and "changed" is the last thing the user clicks on.

So I have a function that reads the JSON string from a textarea, modifies it dependant on what the user has selected (node and value) and then writes it back to the text area for debugging.

function changeJSON(node, value) {
    json = JSON.parse($('#json').val());
    json.selection[node] = value;
    delete json.changed;
    json.changed = {node:value};
    $('#json').val(JSON.stringify(json));
}

"selection" works nicely but "changed" updates to the literal variable name I pass it (in this case node) Ie if I called the function with changeJSON("BC","HC") the JSON string becomes:

{"model":"14","imgsize":"890","selection":{"SC":"BC","PC":"AC","BC":"HC"},"changed":{"node":"HC"}}

I understand what javascript is trying to do but I want the changed element to be what my variable contains ie

,"changed":{"BC","HC"}

and not

,"changed":{"node","HC"}

I'd love someone to tell me what I am doing wrong!?

EDIT

Solved - see below for Quentin explanation as to why and my answer for the code changes necessary - hope it helps others.

I don't think this is the same question, mine is why the literal variable name is used rather than the contents of the variable

The question referenced explains how to resolve the issue, but since you are asking for an explanation.

A variable name is a JavaScript identifier.

A property name in object literal syntax is also a JavaScript identifier (although you can use a string literal instead).

Since an identifier cannot be both a variable and a property name at the same time, you cannot use variables for property names in object literal syntax.

You have to, as described in the referenced question, create the object and then use the variable in square bracket notation.

The solution, as Quentin suggested is to create th object first ie

delete json.changed;
json.changed = {};
json.changed[node] = value;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM