Common operations for Json arrays in Js

Source: Internet
Author: User

We first define a JSON array object as follows:

var persons = [    "Tina"    , age:14}, "Timo", Age:15},    "Lily", Age:16  },    "Lucy", Age:16}]

I. Get the corresponding object based on the object property value

// 1. Get name equals Lily's Object var lily = Persons.filter (P) = {    return p.name = = "Lily "// Print results [{name:" Lily ", age:16}]// Note: the filter () method returns an array of var twins = Persons.filter ((p) + =    {return p.age == +//  Print results [{name: "Lily", Age:16},{name: "Lucy", Age:16}]

Two. Delete one of the objects

//Remove the name equals Tina object, using the Splice () method//1. First we have to get this objectvarTina = Persons.filter ((p) = = {    returnP.name = = "Tina";});//2. Next get the object in the array corresponding to the indexvarindex = Persons.indexof (tina[0]);//3. If it is present, delete it, index > 1 represents the existenceIndex >-1 && persons.splice (index, 1); Console.log (persons);//print result [{name: "Timo", age:15}, {name: "Lily", age:16}, {name: "Lucy", Age:16}]

Three. Modify the property values of one of the objects

// Change the age of name equal to Timo // 1. Get Timo Object var timo = Persons.filter ((p) = =    {return p.name = = "Timo"  ;}); // 2. ModifyAge timo[0].age = 20;

Four. Add an object to the array

// The simplest of the Persons.push ({name: "similar", age:18});

--Note: All of the above operations will have a direct effect on the original array.

Common operations for Json arrays in Js

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.