javascript - 使用来自其他对象的属性值对创建一个新对象

标签 javascript javascript-objects

const ingredients = {
  fruit: 'orange', liquid: 'water', vegetable: 'tomato', spices: 'curry'
};

我想从 ingredients 中挑选一些属性并将它们添加到一个新对象 - shoppingList

现在我是这样做的:

const shoppingList = {};
shoppingList.fruit = ingredients[fruit];
shoppingList.spices = ingredients[spices];

有没有更方便的方法来完成上述操作?我正在设想某种类型的函数,我可以为其提供 ingredientsfruitspices,它将返回具有这些属性的新对象和值(value)观。

最佳答案

您可以使用 reduce根据传递给函数的键生成新对象。

小运行示例:

const ingredients = {
  fruit: 'orange',
  liquid: 'water',
  vegetable: 'tomato',
  spices: 'curry'
};

function pick(keys, obj) {
  const newObj = keys.reduce((result, currentKey) => {
    result[currentKey] = obj[currentKey];
    return result;
  }, {});
  return newObj;
}


const myKeys = ['fruit', 'spices'];
const customObj = pick(myKeys, ingredients);
console.log(customObj);

如果你真的想疯狂,你可以将它添加到 Object.prototype 并直接在对象上调用它。
请注意,这会将 pick 方法添加到所有对象,因此可以考虑将它仅添加到您的某些对象:

const ingredients = {
  fruit: 'orange',
  liquid: 'water',
  vegetable: 'tomato',
  spices: 'curry'
};


Object.prototype.pick = function(keys){
  const newObj = keys.reduce((result, currentKey) => {
    result[currentKey] = this[currentKey];
    return result;
  }, {});
  return newObj;
}

const myKeys = ['fruit', 'spices'];
const customObj = ingredients.pick(myKeys);
console.log(customObj);

关于javascript - 使用来自其他对象的属性值对创建一个新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48029638/

相关文章:

javascript - 从特定远程站点 PHP 抓取信息

javascript - 为什么读取未声明的变量会出现引用错误,但未声明的对象属性在 javascript 中返回未定义?

javascript - Chrome 控制台 - 这个代表 Kendo UI 小部件的东西实际上意味着什么?

javascript - 仅当值不存在时才向对象添加新的数组条目

javascript - document.open 在 Safari 中不起作用

javascript - Jquery - 查找已检查的 radio 并触发同级的点击

javascript - 使用正则表达式获取div内的部分文本

javascript - $ ("#id").val() 返回 dojo.filteringselect 对象的选项文本

Javascript:使用字符串更新机器人的方向不起作用

javascript - Object.assign() 与 angular.extend()