简体   繁体   中英

Change nested object data with javascript

I'd like to affect all items in the array. The end result will be to decodeURIcomponent on each item.

It's not working for me so I decided to change the value of each item to check the code. It doesn't change anything.

Is there a better way of doing this, as really nested $.each functions seems a bit redundant to me.

 $(function() { var hResponse = []; hResponse.push("firstName", "lastName", "location"); var columns = []; columns.push({ "firstName": "Edward", "lastName": "Dane", "location": " Here" }, { "firstName": "Arthur", "lastName": "Dee", "location": "There" }, { "firstName": "Cherry", "lastName": "Red", "location": "OverHere" }); $.each(columns, function (key, value) { $.each(value, function (key1, value2) { value2 = "Meeeeep"; //value2 = decodeURIComponent(value2); }); }); $('#my-table').dynatable({ dataset: { records: columns } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <link href="https://s3.amazonaws.com/dynatable-docs-assets/css/jquery.dynatable.css" rel="stylesheet"/> <script src="https://s3.amazonaws.com/dynatable-docs-assets/js/jquery.dynatable.js"></script> <table id="my-table"> <thead> <th>FirstName</th> <th>LastName</th> </thead> <tbody></tbody> </table> <br> 

JavaScript is all pass-by-value . Assigning a value to a variable does not change the value of another variable or property (except in global and with scope). You have to assign the changed value back to the object property.

With minimal changes to your code:

$.each(columns, function (key, value) {
    $.each(value, function (key1, value2) {
        value[key] = decodeURIComponent(value2);
    });
});

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