Pregunta

I've a function that gets 2 values name and value and now I'd like to turn them into a JSON, so for example lets say ive this function

function addin(name,val)

and then i'll call it

addin("age","28") -> this will return -> {age: 28}
addin("name","Roni") -> {name: Roni}

I've tried many things to find out how to make it done, Im getting many data so I tried this

var full_js = { };

    _.forEach(data, function(val,name) {

        full_js.name = val;
        console.log(JSON.stringify(full_js));

    });

again it can be any value and any name both of them are Random Strings. but its not working, I get it as {"name": "Roni"} and {"name": "55"}. thanks for the help.

¿Fue útil?

Solución

use a different notation:

function addin(name, val) {
    var full_js = {};
    full_js[name] = val;

    return JSON.stringify(full_js);
}

Ex:

enter image description here

at the moment you are always assigning the value to the name key, instead of the dynamic name key, keep in mind that the key will always be the string representation of the variable used.

for example, addin({}, 'rony'), will return {"[object Object]":"test"}

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top