skip to Main Content

I can’t seem to format my array that is being saved to localStorage.
Can you change the index value of an array?
I have an array object like this:

const myArray = [{id: 41, name: "x"}, {id: 42, name: "y"}]

But I want to make it like this:

const myArray = [ 41: {id:41, name:"x" }, 42: {id:41, name:"y" }}

So the id of the object becomes the index of the array

If that is not possible then like this should be fine:

const myArray = [ {41: {id:41, name:"x"} }, {42: {id:41, name:"y"}}]

So basically the id of the object becomes either the index or a container object for that object.

2

Answers


  1. You can achieve this by transforming your array into an object where the keys are the IDs and the values are the corresponding objects. Here’s how you can do it:

    const myArray = [{id: 41, name: "x"}, {id: 42, name: "y"}];
    
    // Convert the array into an object
    const transformedArray = myArray.reduce((acc, obj) => {
        acc[obj.id] = obj;
        return acc;
    }, {});
    
    console.log(transformedArray);
    
    

    This will give you the desired result where the IDs are the keys of the object:

    {
      41: {id: 41, name: "x"},
      42: {id: 42, name: "y"}
    }
    

    If you want to wrap each object with its ID, you can use a slightly different approach:

    const transformedArray = myArray.reduce((acc, obj) => {
        acc.push({[obj.id]: obj});
        return acc;
    }, []);
    
    console.log(transformedArray);
    

    This will give you the array where each object is wrapped with its ID:

    [
      {41: {id: 41, name: "x"}},
      {42: {id: 42, name: "y"}}
    ]
    
    Login or Signup to reply.
  2. You cannot directly change the key of an element in an array to a specific value like an object’s property. Butyou can create an object where the keys are the IDs and the values are the corresponding objects.

    const myArray = [{id: 41, name: "x"}, {id: 42, name: "y"}];
    const myObject = {};
    
    // Convert array to object
    myArray.forEach(item => {
        myObject[item.id] = item;
    });
    
    // Now myObject will look like:
    // { 41: {id:41, name:"x"}, 42: {id:42, name:"y"} }
    
    // If you still need it as an array of objects with IDs as keys:
    const newArray = Object.keys(myObject).map(key => ({ [key]: myObject[key] }));
    
    // Now newArray will look like:
    // [ {41: {id:41, name:"x"} }, {42: {id:42, name:"y"}} ]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search