JSON數組操作
我們首先定義一個json數組對象如下:
var persons = [ {name: "tina", age: 14}, {name: "timo", age: 15}, {name: "lily", age: 16}, {name: "lucy", age: 16} ]
一. 根據對象屬性值得到相應對象
//1. 獲取 name 等於 lily 的對象 var lily = persons.filter((p) => { return p.name == "lily"; }); console.log(lily); //打印結果 [{name: "lily", age: 16}] //注:filter()方法返回的是一個數組 var twins = persons.filter((p) => { return p.age == 16; }); console.log(twins); //打印結果 [{name: "lily", age: 16},{name: "lucy", age: 16}]
二. 刪除其中一個對象
//刪除 name 等於 tina 的對象,利用splice()方法 //1. 首先我們要得到這個對象 var tina = persons.filter((p) => { return p.name == "tina"; }); //2. 其次得到這個對象在數組中對應的索引 var index = persons.indexOf(tina[0]); //3. 如果存在則將其刪除,index > -1 代表存在 index > -1 && persons.splice(index, 1); console.log(persons); //打印結果 [{name: "timo", age: 15}, {name: "lily", age: 16}, {name: "lucy", age: 16}]
三. 修改其中一個對象的屬性值
//將 name 等於 timo 的 age 修改為 20 //1. 得到 timo 對象 var timo = persons.filter((p) => { return p.name == "timo"; }); //2. 修改age timo[0].age = 20;
四. 往數組中添加一個對象
persons.push({name: "similar", age: 18});
五.將兩個json數組進行拼接
var c = a.concat(b);
JSON對象的操作
- JSON對象是無序的
- 對象可以包含多個key/value(鍵/值)對
- key 必須是字符串,value 可以是合法的 JSON 數據類型(字符串, 數字, 對象, 數組, 布爾值或 null)
訪問對象值
可以使用點號(.)來訪問對象的值:
var myObj, x; myObj = { "name":"runoob", "alexa":10000, "site":null }; x = myObj.name;
可以使用中括號([])來訪問對象的值:
var myObj, x; myObj = { "name":"runoob", "alexa":10000, "site":null }; x = myObj["name"];
使用 for-in 來循環對象的屬性:
var myObj = { "name":"runoob", "alexa":10000, "site":null }; for (x in myObj) { document.getElementById("demo").innerHTML += x + "<br>"; }
在 for-in 循環對象的屬性時,使用中括號([])來訪問屬性的值:
var myObj = { "name":"runoob", "alexa":10000, "site":null }; for (x in myObj) { document.getElementById("demo").innerHTML += myObj[x] + "<br>"; }
json數組拼接
var fileNameArray = $ProjectAuditTeacherCenter.fileInfoArray.map(function (m) { return m.fileName; }); var filePathArray = $ProjectAuditTeacherCenter.fileInfoArray.map(function (m) { return m.filePath; }); $("#ProjectFile_AttachOldName").val(fileNameArray.join(",")); $("#ProjectFile_AttachPath").val(filePathArray.join(","));