get one item from an array of name,value JSON

后端 未结 7 938
孤城傲影
孤城傲影 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:04

    I know this question is old, but no one has mentioned a native solution yet. If you're not trying to support archaic browsers (which you shouldn't be at this point), you can use array.filter:

    var arr = [];
    arr.push({name:"k1", value:"abc"});
    arr.push({name:"k2", value:"hi"});
    arr.push({name:"k3", value:"oa"});
    
    var found = arr.filter(function(item) { return item.name === 'k1'; });
    
    console.log('found', found[0]);
    Check the console.

    You can see a list of supported browsers here.

    In the future with ES6, you'll be able to use array.find.

    0 讨论(0)
  • 2020-12-13 02:16

    I don't know anything about jquery so can't help you with that, but as far as Javascript is concerned you have an array of objects, so what you will only be able to access the names & values through each array element. E.g arr[0].name will give you 'k1', arr[1].value will give you 'hi'.

    Maybe you want to do something like:

    var obj = {};
    
    obj.k1 = "abc";
    obj.k2 = "hi";
    obj.k3 = "oa";
    
    alert ("obj.k2:" + obj.k2);
    
    0 讨论(0)
  • 2020-12-13 02:17

    To answer your exact question you can get the exact behaviour you want by extending the Array prototype with:

    Array.prototype.get = function(name) {
        for (var i=0, len=this.length; i<len; i++) {
            if (typeof this[i] != "object") continue;
            if (this[i].name === name) return this[i].value;
        }
    };
    

    this will add the get() method to all arrays and let you do what you want, i.e:

    arr.get('k1'); //= abc
    
    0 讨论(0)
  • 2020-12-13 02:19

    You can't do what you're asking natively with an array, but javascript objects are hashes, so you can say...

    var hash = {};
    hash['k1'] = 'abc';
    ...
    

    Then you can retrieve using bracket or dot notation:

    alert(hash['k1']); // alerts 'abc'
    alert(hash.k1); // also alerts 'abc'
    

    For arrays, check the underscore.js library in general and the detect method in particular. Using detect you could do something like...

    _.detect(arr, function(x) { return x.name == 'k1' });
    

    Or more generally

    MyCollection = function() {
      this.arr = [];
    }
    
    MyCollection.prototype.getByName = function(name) {
      return _.detect(this.arr, function(x) { return x.name == name });
    }
    
    MyCollection.prototype.push = function(item) {
      this.arr.push(item);
    }
    
    etc...
    
    0 讨论(0)
  • 2020-12-13 02:20

    The easiest approach which I have used is

    var found = arr.find(function(element) {
             return element.name === "k1";
     });
    
    //If you print the found :
    console.log(found);
    => Object { name: "k1", value: "abc" }
    
    //If you need the value
    console.log(found.value)
    => "abc"
    

    The similar approach can be used to find the values from the JSON Array based on any input data from the JSON.

    0 讨论(0)
  • 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);

    0 讨论(0)
提交回复
热议问题