json数组
let persons = [
{id:1,name: "Alex", age: 18},
{id:2,name: "Teamo", age: 15},
{id:3,name: "Lily", age: 16},
{id:4,name: "Lucy", age: 16},
{id:5,name: "Tom", age: 19}
]
新增一个对象
let alice = {name: ''Alice", age: 18};
persons.push(alice);
删除其中一个对象
//删除 name 等于 Alex的对象,利用splice()方法
//1. 首先我们要得到这个对象
let alex = persons.filter((p) => {
return p.name == "Alex";
});
//2. 其次得到这个对象在数组中对应的索引
let index = persons.indexOf(alex[0]);
//3. 如果存在则将其删除,index > -1 代表存在
index > -1 && persons.splice(index, 1);
console.log(persons);
//打印结果 [{name: "Teamo", age: 15}, {name: "Lily", age: 16}, {name: "Lucy", age: 16}, {name: "Tom", age: 19}]
修改其中一个对象的属性值
//将 name 等于 Teamo的 age 修改为 20
//1. 得到 timo 对象
let teamo= persons.filter((p) => {
return p.name == "Teamo";
});
//2. 修改age
teamo[0].age = 20;
查询筛选 filter
根据对象属性值得到相应对象
let twins = persons.filter((p) => {
return p.age == 16;
});
console.log(twins); //打印结果 [{name: "Lily", age: 16},{name: "Lucy", age: 16}]
网友评论