【问题标题】:How to change indexes keys an array of object in JavaScript如何在 JavaScript 中更改索引键一个对象数组
【发布时间】:2021-02-24 06:06:19
【问题描述】:

我有一个对象数组[{name:'abc'},{name:'def'},{name:'ghi'}]。当我在这个数组上循环map() 时,我得到像[0:{name:'abc'},1:{name:'def'},2:{name:'ghi'}] 这样的数组。我想将索引号更改为字符串值,例如['string1':{name:'abc'},'string2':{name:'def'},'string3:{name:'ghi'}]。实际上它会将 (0, 1,2) 索引更改为 string 。我试过但没有找到任何解决方案。有人可以帮我解决这个问题。 ?

任何简单的例子都会受到赞赏

谢谢

【问题讨论】:

  • ['string1':{name:'abc'},'string2':{name:'def'},'string3:{name:'ghi'}] 无效
  • 你是怎么尝试的?
  • “我试过了,但没有找到任何解决方案”告诉我们你的尝试
  • “我知道,但我有要求” - 由于语法无效 o.O
  • 是的,JS 中不能有关联数组,[string1:{name:'abc'}] 无效,但是,{string1:{name:'abc'}} 有效(对象)

标签: javascript arrays reactjs ecmascript-6 ecmascript-2016


【解决方案1】:

您需要一个允许按给定键索引的数据结构,您应该尝试objectMap。如果您只是想做一些简单的事情,请使用object

有了这个,你应该有:

const names = {
  string1: {name:'abc'},
  string2: {name:'def'},
  string3: {name:'ghi'}
}

但我想可以简化为:

const names = {
  string1: 'abc',
  string2: 'def',
  string3: 'ghi'
}

但是如果你想走很长的路,这可以给你类似的东西。

const names = [{name:'abc'},{name:'def'},{name:'ghi'}];
const entries = Object.fromEntries(names.entries());
const mappedNames = Object.keys(entries).map(key => [`string${key}`, entries[key]])

const newNames = Object.fromEntries(mappedNames)

这会给你:

{
  string0: {name:'abc'},
  string1: {name:'def'},
  string2: {name:'ghi'}
}

但是你不能改变数组索引的值。

【讨论】:

    【解决方案2】:

    您描述的['string1':{name:'abc'},'string2':{name:'def'},'string3:{name:'ghi'}] 语法无效。相反,结合for-of 循环和object literals

    let obj = {};
    let ind = 0;
    for (const object of /*array name*/) {
      obj["string" + ind] = object;
      ind += 1;
    

    【讨论】:

      猜你喜欢
      • 2021-04-22
      • 1970-01-01
      • 1970-01-01
      • 2021-09-28
      • 1970-01-01
      • 1970-01-01
      • 2019-08-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多