get one item from an array of name,value JSON

后端 未结 7 961
孤城傲影
孤城傲影 2020-12-13 01:33

I have this array:

var arr = [];
arr.push({name:\"k1\", value:\"abc\"});
arr.push({name:\"k2\", value:\"hi\"});
arr.push({name:\"k3\", value:\"oa\"});
         


        
7条回答
  •  自闭症患者
    2020-12-13 02:25

    Find one element

    To find the element with a given name in an array you can use find:

    arr.find(item=>item.name=="k1");
    

    Note that find will return just one item (namely the first match):

    {
      "name": "k1",
      "value": "abc"
    }
    

    Find all elements

    In your original array there's only one item occurrence of each name.

    If the array contains multiple elements with the same name and you want them all then use filter, which will return an array.

    var arr = [];
    arr.push({name:"k1", value:"abc"});
    arr.push({name:"k2", value:"hi"});
    arr.push({name:"k3", value:"oa"});
    arr.push({name:"k1", value:"def"});
    
    var item;
    
    // find the first occurrence of item with name "k1"
    item = arr.find(item=>item.name=="k1");
    console.log(item);
    
    // find all occurrences of item with name "k1"
    // now item is an array
    item = arr.filter(item=>item.name=="k1");
    console.log(item);

    Find indices

    Similarly, for indices you can use findIndex (for finding the first match) and filter + map to find all indices.

    var arr = [];
    arr.push({name:"k1", value:"abc"});
    arr.push({name:"k2", value:"hi"});
    arr.push({name:"k3", value:"oa"});
    arr.push({name:"k1", value:"def"});
    
    var idx;
    
    // find index of the first occurrence of item with name "k1"
    idx = arr.findIndex(item=>item.name == "k1");
    console.log(idx, arr[idx].value);
    
    // find indices of all occurrences of item with name "k1"
    // now idx is an array
    idx = arr.map((item, i) => item.name == "k1" ? i : '').filter(String);
    console.log(idx);

提交回复
热议问题