Home > Net >  Map Nested Array in ES6
Map Nested Array in ES6

Time:12-15

I have here a nested array. The inner array has only one data. Is there a way that I would improve this? Like minimize using [0]? Using modern JS.

NOTE: I rename status to myStatus

let response = [
    {
        "data": [
            {
                "name": "Hello",
                "status": "There"
            }
        ],
    
    },
    {
        "data": [
            {
                "name": "Hello",
                "status": "There"
            }
        ],
    
    }
];


const finalDatas = response?.map((value) => {
 return {
   name: value?.data?.[0]?.name,
   myStatus: value?.data?.[0]?.status
 };
});
      
console.log(finalDatas)

CodePudding user response:

You can try this:

const response = [
    {
        "data": [
            {
                "name": "Hello",
                "status": "There"
            }
        ],
    
    },
    {
        "data": [
            {
                "name": "Hello",
                "status": "There"
            }
        ],
    
    },
    {
        "data": [ // name: undefined, status: null
            {
                "status": null
            }
        ],
    
    },
    {
        "data": [ // data array with empty object
            {}
        ],
    },
{
        "data": [], //empty array - this doesn't end up in the result list
    },
];

const res = response.flatMap(({data}) => [...data].map(item => {
    return {
      name: item.name,
      myStatus: item.status,
    };
}));
console.log(res);

EDIT: I added more cases to the snippet. As you can see this code produces an entry in the result list as long there is an object inside the data list.

CodePudding user response:

try with the below code snippet. This might be helpful.

    let response = [
    {
        "data": [
            {
                "name": "Hello",
                "status": "There"
            }
        ],
    
    },
    {
        "data": [
            {
                "name": "Hello",
                "status": "There"
            }
        ],
    
    }
];

let renameKey = ( obj, oldKey, newKey ) => {
  obj[newKey] = obj[oldKey];
  delete obj[oldKey];
  return obj
}

let output = response.map(data => renameKey(data.data[0], "status", "myStatus"));
console.log(output);

CodePudding user response:

You can use flatMap and a spread

Without renaming

const finalDatas = response.flatMap(({data}) => [...data]);

UPDATE after comment: the code needs to be somewhere

const ren = (obj, oldKey, newKey) => {
  obj = obj.pop();
  return delete Object.assign(obj, {[newKey]: obj[oldKey]})[oldKey], obj;
}
const finalDatas = response.map(({data}) => ren(data, "status", "myStatus"));

console.log(finalDatas);
<script>
  let response = [{
      "data": [{
        "name": "Hello",
        "status": "There"
      }],

    },
    {
      "data": [{
        "name": "Hello",
        "status": "There"
      }],

    }
  ];
</script>

  • Related