使用javascript更改嵌套对象数据

时间:2015-03-26 19:28:18

标签: javascript jquery

我想影响数组中的所有项目。最终结果将是decodeURIcomponent每个项目。

它不适合我,所以我决定更改每个项目的值以检查代码。它没有改变任何东西。

有没有更好的方法,因为真正嵌套的$.each函数对我来说似乎有点多余。



$(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>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:5)

JavaScript全是pass-by-value。为变量赋值不会更改另一个变量或属性的值(全局和with范围除外)。您必须将更改的值分配回对象属性。

对代码进行最少的更改:

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