简体   繁体   中英

Return a new object whose properties are those in the given object and whose keys are present in the given array.

:) I need to return a new object whose properties are those in the given object and whose keys are present in the given array.

code attempt:

var arr = ['a', 'c', 'e'];
var obj = {
  a: 1,
  b: 2,
  c: 3,
  d: 4
};

function select(arr, obj) {
 var result = {};
 var array = [];
 for (var key in obj){
   array.push(key);
 }
var num = arr.length + obj.length; 
    for (var i = 0; i < num; i++) {
     for(var j = 0; j < num; j++) {
       if (arr[i] === array[j]) {

       result.array[i] = obj.arr[i];
     }
     }
    }
    return result;
}

(incorrect) result:

{}

desired result:

// --> { a: 1, c: 3 }

Any advice? Thank you! :)

You could iterate the given keys, test if it is a key in the object and assign the value to the same key in the result object.

 function select(arr, obj) { var result = {}; arr.forEach(function (k) { if (k in obj) { result[k] = obj[k]; } }); return result; } var arr = ['a', 'c', 'e'], obj = { a: 1, b: 2, c: 3, d: 4 }; console.log(select(arr, obj)); 

Longer, but more readable version:

 var arr = ['a', 'c', 'e'], obj = {a:1,b:2,c:3,d:4}, hash = {}; arr.forEach(function(v){ //iterate over each element from arr Object.keys(obj).some(function(c){ //check if any key from obj is equal to iterated element from arr if (v == c) { hash[v] = obj[c]; //if it is equal, make a new key inside hash obj and assign it's value from obj to it } }); }); console.log(hash); 

Short version:

 var arr = ['a', 'c', 'e'], obj = {a:1,b:2,c:3,d:4}, hash = {}; arr.forEach(v => Object.keys(obj).some(c => v == c ? hash[v] = obj[c] : null)); console.log(hash); 

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