简体   繁体   中英

javascript map object values

I have an array of objects:

[{a:1;b:2},{a:3;b:4},{a:5;b:6},{a:7;b:8},{a:9;b:10}]

And the input is the value for a, like 1, and I want the output be the value of corresponding b, which return 2 for example.

I have a naive method to loop through the array and return the result. I'm wondering whether there's better solutions? Like map the array to an array of the values of a, and get the index of input then get the output by using the index that we get.

One more explanation is that the value of a is identical, they are not values, examples are used to illustrate the problem.

example:

INPUT: 1 OUTPUT:2

INPUT: 3 OUTPUT:4

INPUT: 5 OUTPUT:6

INPUT: 7 OUTPUT:8

And my code is like this:

var test=function(obj){
    var a=obj.map(function(item){
        return item.a;
    })
    return obj[a.indexof("1")].b;
}

You can preprocess the array of objects to create a single object, which will hold the values of a as keys and the values of b as corresponding values, with Array.prototype.reduce , like this

> var d = [{a: 1, b: 2}, {a: 3, b: 4}, {a: 5, b: 6}, {a: 7, b: 8}, {a: 9, b: 10}];
undefined
> var lookup = d.reduce(function (result, currentObject) {
...     result[currentObject.a] = currentObject.b;
...     return result;
... }, {});
undefined
> lookup
{ '1': 2, '3': 4, '5': 6, '7': 8, '9': 10 }

Then you can get the value corresponding to the number from the lookup , like this

> lookup[5]
6
> lookup[9]
10

If the value you are looking for is not present in the lookup , you will get undefined .

> lookup[11]
undefined

I think that could be nice

var obj = [{a:1,b:2},{a:3,b:4},{a:5,b:6},{a:7,b:8},{a:9,b:10}];

function get_it(_v){
    for(x=0;x<obj.length;x++) if(obj[x].a == _v) return obj[x].b;
}

console.log(get_it(prompt('Insert your number:')));

This does what you want. However, you need to think of the possible case when there are more objects in the array with a matching needle.

function getBbyA(input, needle) {
    for (var index in input) {
        if (input[index].a === needle) {
            return input[index].b;
        }
    }
    return null;
}

 var arr = [{a:1,b:2},{a:3,b:4},{a:5,b:6},{a:7,b:8},{a:9,b:10}]; function getIt(num){ return arr.filter(function(item){ return item.a === num; }).pop().b } alert(getIt(5)); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM