[英]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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.