Javascript function issue

I have a JS function.

responseData:function(resp){
    this.jsondata = eval('(' + resp + ')');
    this.propList = [];
    for (var i = 0;i<this.jsondata.length;i++) {
        for (obj in this.jsondata[i]) {
            alert(obj); //shows the property name of obj
            this.propList.push({
                obj : this.jsondata[i][obj] //insert only simple obj string
            });
        }
    }
    return this.propList;
}

I want to insert the property name and value into my propList, but instead of pasting the property name, this function inserts a simple "obj" as a string. What am I doing wrong?

hi Stefan

+3
source share
1 answer

Change the loop to,

    for (obj in this.jsondata[i]) {
        alert(obj); //shows the property name of obj
        var item = {};
        item[obj] = this.jsondata[i][obj];
        this.propList.push(item);
    }

When you use a literal object to create an object, property names are not evaluated as variables. To specify the property name of an object using the current value of the variables, you must use the format obj[variable]. This will create a property in obj, whose name will be the same as the current value variable.

+4
source

Source: https://habr.com/ru/post/1738944/


All Articles