【问题标题】:How to create object key dynamically in JS?如何在 JS 中动态创建对象键?
【发布时间】:2020-04-25 04:15:30
【问题描述】:

我试图在构造对象时动态映射键,它没有将 ID 创建为键。

main.js

const data = [
 {
  "ID":"Bellaire",
  "Name":"Bellaire", 
  "Address": "1st Ave"
 },
 {
  "ID":"Bellaire",
  "Name":"Bellaire",
  "Address": "1st Ave"
 },
 {
  "ID":"Champions Forest",
  "Name":"Champions Forest",
   "Address": "2nd Ave"
 }
 ]
function test(data,id){
 const filterData = data.filter(e => {
   if(e.ID === id) {
     return true;
   }
 });
const finalResponse = {
  filterData[0].ID: ["other Details"]
}
 return finalResponse;
}
console.log(test(data,"Bellaire"));

预期输出

[ { "Bellaire": ["other Details"] } ]

【问题讨论】:

标签: javascript arrays ecmascript-6 filter


【解决方案1】:

由于filterData[0].ID 返回一个字符串,并且为了将其设置为键,您只需将其包装为[filterData[0].ID]

const finalResponse = {
   [filterData[0].ID] : ["other Details"]
}

演示:

const data = [{ID:"Bellaire",Name:"Bellaire",Address:"1st Ave"},{ID:"Bellaire",Name:"Bellaire",Address:"1st Ave"},{ID:"Champions Forest",Name:"Champions Forest",Address:"2nd Ave"}];

function test(data, id) {
  const filterData = data.filter(e => {
    return e.ID === id
  });
  const finalResponse = {
    [filterData[0].ID] : ["other Details"]
  }
  return finalResponse;
}
console.log(test(data, "Bellaire"));

【讨论】:

    猜你喜欢
    • 2020-10-11
    • 1970-01-01
    • 2023-02-07
    • 1970-01-01
    • 2020-03-01
    • 2018-09-21
    • 2019-10-20
    • 2011-01-23
    • 2011-04-29
    相关资源
    最近更新 更多