通过迭代数组将方法分配给对象

时间:2016-03-02 19:55:55

标签: javascript arrays object ecmascript-6

在ES5中,我知道可以通过以下方式使用<?php /** * @ORM\Entity * @ORM\HasLifecycleCallbacks * @ORM\Table(name = "USER") * * @JMS\ExclusionPolicy("all") * @JMS\AccessorOrder("custom", custom = { "id", "firstName", "lastName" }) */ class User { /** * @ORM\Id * @ORM\Column(name = "id", type = "integer", options={"unsigned"=true}) * @ORM\GeneratedValue(strategy = "IDENTITY") * @JMS\SerializedName("id") * @JMS\Expose * @JMS\Type("integer") * @var int */ private $id; /** * @ORM\Column(name = "firstName", type = "string", length = 255) * @JMS\SerializedName("firstName") * @JMS\Expose * @JMS\Type("string") * @var string */ private $firstName; /** * @ORM\Column(name = "lastName", type = "string", length = 255) * @JMS\SerializedName("lastName") * @JMS\Expose * @JMS\Type("string") * @var string */ private $lastName; /** * @ORM\OneToMany(targetEntity = "Post", mappedBy = "user", cascade = { "persist" }, fetch="LAZY") * @JMS\Expose * @var ArrayCollection<Post> */ private $posts; public function getId() { return $this->id; } public function getFirstName() { return $this->firstName; } public function getLastName() { return $this->lastName; public function getPosts() { return $this->posts->toArray(); } } 循环为对象分配方法:

forEach

在ES2015(或ES6)中,是否可以与创建对象一起定义这些方法?以下是我希望如何工作的示例:

var myMethods = [
  {
    name: 'start',
    src: someFn
  },
  {
    name: 'stop',
    src: someOtherFn
  }
];

var myObject = {};

myMethods.forEach(function(method) {
  myObject[method.name] = method.src;
});

最终结果如下:

// example
const myObject = {
  [...myMethods.map((method) => method.name)]: [...myMethods.map(method) => method.src)]
}

如果一种迭代这些方法并将它们分配给const myObject = { start: someFn, stop: someOtherFn } 的方法,我很乐意重构myObject数组,以便这是可能的。

最终目标是能够在外部模块中分配这些方法,而不必复制定义。

3 个答案:

答案 0 :(得分:5)

是的,您可以将Object.assign和spread运算符与计算属性名称结合使用

var myObject = Object.assign({}, ...myMethods.map(({name, src}) => ({[name]: src})));

首先,我们将myMethods映射到一个小属性对象的数组,其关键字由name属性的值和src属性的值给出。然后我们使用扩展运算符...将这些作为参数传递给Object.assignObject.assign然后将它们粘在一起给我们。

答案 1 :(得分:3)

Reduce应该为你做的伎俩。请注意,可选的第二个参数用于从开头的空对象开始。

&#13;
&#13;
var myMethods = [{
  name: 'start',
  src: function() {
    console.log('started')
  }
}, {
  name: 'stop',
  src: function() {
    console.log('stopped')
  }
}];

var myObject = myMethods.reduce((obj, method) => {
  obj[method.name] = method.src;
  return obj;
}, {})


console.log(myObject)
myObject.start()
myObject.stop()
&#13;
&#13;
&#13;

答案 2 :(得分:0)

尝试在myObject assignnemts

的同一行分配myMethods
var myObject = {};

someFn = function(){console.log(this)};
someOtherFn = function(){console.log(this)};

var myObject = {};

someFn = function(){};
someOtherFn = function(){}

var myMethods = [
  {
    name: (myObject["start"] = "start"),
    src: (myObject["start"] = someFn)
  },
  {
    name: (myObject["stop"] = "stop"),
    src: (myObject["stop"] = someOtherFn)
  }
];