Js中對JSON數組的常用操作


Js中對JSON數組的常用操作

JSON數組操作

我們首先定義一個json數組對象如下:

var persons = [
    {name: "tina", age: 14},
    {name: "timo", age: 15},
    {name: "lily", age: 16},
    {name: "lucy", age: 16}
]
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

一. 根據對象屬性值得到相應對象

//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}]
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

二. 刪除其中一個對象

//刪除 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}]
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

三. 修改其中一個對象的屬性值

//將 name 等於 timo 的 age 修改為 20

//1. 得到 timo 對象
var timo = persons.filter((p) => {
    return p.name == "timo";
});

//2. 修改age
timo[0].age = 20;
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

四. 往數組中添加一個對象

persons.push({name: "similar", age: 18});
 
  • 1

五.將兩個json數組進行拼接

var c = a.concat(b);
 
  • 1

JSON對象的操作

  • JSON對象是無序的
  • 對象可以包含多個key/value(鍵/值)對
  • key 必須是字符串,value 可以是合法的 JSON 數據類型(字符串, 數字, 對象, 數組, 布爾值或 null)

訪問對象值

可以使用點號(.)來訪問對象的值:

var myObj, x;
myObj = { "name":"runoob", "alexa":10000, "site":null };
x = myObj.name;
 
  • 1
  • 2
  • 3

可以使用中括號([])來訪問對象的值:

var myObj, x;
myObj = { "name":"runoob", "alexa":10000, "site":null };
x = myObj["name"];
 
  • 1
  • 2
  • 3

使用 for-in 來循環對象的屬性:

var myObj = { "name":"runoob", "alexa":10000, "site":null };
for (x in myObj) {
    document.getElementById("demo").innerHTML += x + "<br>";
}
 
  • 1
  • 2
  • 3
  • 4

在 for-in 循環對象的屬性時,使用中括號([])來訪問屬性的值:

var myObj = { "name":"runoob", "alexa":10000, "site":null };
for (x in myObj) {
    document.getElementById("demo").innerHTML += myObj[x] + "<br>";
}
 
  • 1
  • 2
  • 3
  • 4

 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM