Search code examples
javascriptarraysreactjsecmascript-6ecmascript-2016

How to change indexes keys an array of object in JavaScript


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


Solution

  • 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.