最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Map an ID array to a string array using via an object list - Stack Overflow

programmeradmin2浏览0评论
var myIds = [3, 4, 2];

var myObj = [
    {id:1, name:'one'}, 
    {id:2, name:'two'},
    {id:3, name:'tree'},
    {id:4, name:'four'}];

// need to obtain ['tree', 'four', 'two']

var idsToNames= function(ids, objects) {
    var myNames = myIds.map(function(id){
        // transform id to name
        foreach(o in objects){
            if (i.id == id) 
                return o.name;
        }
    });
    return myNames;
}

Is it the optimal way to transform a id array into a name array?

var myIds = [3, 4, 2];

var myObj = [
    {id:1, name:'one'}, 
    {id:2, name:'two'},
    {id:3, name:'tree'},
    {id:4, name:'four'}];

// need to obtain ['tree', 'four', 'two']

var idsToNames= function(ids, objects) {
    var myNames = myIds.map(function(id){
        // transform id to name
        foreach(o in objects){
            if (i.id == id) 
                return o.name;
        }
    });
    return myNames;
}

Is it the optimal way to transform a id array into a name array?

Share Improve this question edited Nov 27, 2015 at 16:31 thefourtheye 240k53 gold badges465 silver badges500 bronze badges asked Nov 27, 2015 at 16:23 sergeserge 15.2k41 gold badges142 silver badges234 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

First transform your object like this

var newMyObj = myObj.reduce(function(result, currentObject) {
  result[currentObject.id] = currentObject.name;
  return result;
}, {});

console.log(newMyObj);
// { '1': 'one', '2': 'two', '3': 'three', '4': 'four' }

You can actually create the newMyObj by iterating the array myObj, like this as well

var newMyObj = {};
for (var i = 0; i < myObj.length; i += 1) {
  newMyObj[myObj[i].id] = myObj[i].name;
}

Now, you can simply iterate myIds and pick values from newMyObj, like this

console.log(myIds.map(function(id) { return newMyObj[id]; }));
// [ 'three', 'four', 'two' ]

If your environment supports ECMAScript 2015's Arrow functions, this can be written succinctly as

console.log(myIds.map((id) => newMyObj[id]));
// [ 'three', 'four', 'two' ]

By transforming your original myObj to newMyObj you will be getting constant time lookup. Otherwise you have to iterate the myObj array for every element in the myIds and runtime plexity will bee O(n*m).

发布评论

评论列表(0)

  1. 暂无评论