javascript 将对象添加到数组

javascript adding object to an array

this.journeyIds = ["source", "destination"];
this.journeyDetails = [];

this.journeyIds.map((id)=>{
    this.journeyDetails.push({
        id: this.el("#" + id).inputValue
    });
});

我想要像 [{Source : "LMP"}, {Destination : "LKO"}] 这样的数组; 即我想将 Id 作为对象

中的键

谢谢!

您似乎希望将 id 作为对象的键。在 id

周围使用 []
this.journeyIds = ["source", "destination"];
this.journeyDetails = [];

this.journeyIds.map((id) => {
                this.journeyDetails.push({[id] :
this.el("#"+id).inputValue});
            });

我没有函数 this.el() 所以这里是一个数组,你可以用函数调用替换它 (this.el["#"+id].inputValue => this.el("#"+id).inputValue

this.journeyIds = ["source", "destination"];
this.journeyDetails = [];
this.el = {
  "#source": {inputValue: "foo"},
  "#destination": {inputValue: "bar"}
}

this.journeyIds.forEach((id) => {
    let temp = {};
    temp[id] = this.el["#"+id].inputValue;
    this.journeyDetails.push(temp);
});

console.log(this.journeyDetails)