-1

I have an array of object , [{name:'abc'},{name:'def'},{name:'ghi'}]. When I loop map() on this array I am getting array like [0:{name:'abc'},1:{name:'def'},2:{name:'ghi'}]. I want to change index number to string values like ['string1':{name:'abc'},'string2':{name:'def'},'string3:{name:'ghi'}]. Actually it will change ( 0, 1,2 ) indexes to string . I tried but didn't find any solution . Could someone please help me how to resolve this issue . ?

any simple example will be appreciated

Thanks

JS Guy
  • 11
  • 1
  • 2

2 Answers2

0

You need a data structure that allows indexing by a given key, you should try an object or a Map. Use an object if you're just trying to do something simple.

With that, you should have:

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

But I guess it can be simplified to this:

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

But if you want to go the long way, which can give you something similar.

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)

which would give you:

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

But you can't change the value of an array index.

Joshua
  • 589
  • 1
  • 5
  • 19
0

The syntax you described ['string1':{name:'abc'},'string2':{name:'def'},'string3:{name:'ghi'}] is invalid. Instead, combine for-of loops and object literals.

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