如何更改 JavaScript 中对象数组的索引键

How to change indexes keys an array of object in JavaScript

我有一个对象数组,[{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 。我试过但没有找到任何解决方案。有人可以帮我解决这个问题吗? ?

任何简单的例子将不胜感激

谢谢

您需要一个允许通过给定键进行索引的数据结构,您应该尝试 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'}
}

但您不能更改数组索引的值。

您描述的语法 ['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;