Search code examples
javascriptarraysreactjsreact-nativejavascript-objects

How to change array name inside of an object


Guys Im a bit new to javascript. I have the following code. I need to assign a string name to the data object. How can I convert this object

const obj= { data: [
    { name: "subject", note: "note", time: "12:30-1:30" },
    { name: "subject", note: "note", time: "12:30-1:30" },
  ],}

as an example

const obj= { 'objectName': [
    { name: "subject", note: "note", time: "12:30-1:30" },
    { name: "subject", note: "note", time: "12:30-1:30" },
  ],}

Solution

  • sadly you can't directly change the name of a key. But you can create a new one and delete the old one.

    const obj= { data: [
        { name: "subject", note: "note", time: "12:30-1:30" },
        { name: "subject", note: "note", time: "12:30-1:30" },
      ]}
    
    obj.newName = obj.data;
    delete obj.data;
    
    console.log(obj)