Search code examples
javascriptjavascript-objects

Update Ugly Object Keys Using Another Array


Below array is called Data, it's array of objects with keys like "marketValue"

enter image description here

Below array is called Columns, it's array of objects with each has Header (Pretty name for columns) and id (Ugly name for columns)

enter image description here

How to scroll through Data and update all ugly keys like this "marketValue" to "Market Value" using columns array?

This is how far I got, but it doesn't work, it returns undefined for every singe row:

 let PrettyData = Data.map((row) =>
    Object.entries(row).forEach(
      (key) => {
        let newKey = columns.filter((colRow) => colRow.id === key[0]);
        let obj = {newKey: key[1]}
        return obj;
      }
    )
  );

Solution

  • If I understand correctly, you want to update the the keys of each object in data with the Header value of that columns object. This should do it:

    const prettyMapping = {};
    columns.forEach((column)=>{
        prettyMapping[column.id] = column.Header
    });
    const PrettyData = Data.map((row)=>{
        const prettyRow = {};
        Object.keys(row).forEach((column)=>{
            prettyRow[prettyMapping[column]] = row[column]
        });
        return prettyRow
    });
    
    1. Go through the columns and create a mapping of header to id.
    2. Map over the rows. Map will create a new array with whatever is returned from each original row iteration
    3. In each row iteration, create the newly formatted row using our mapping from before.

    For this case:

    const Data = [{qty:1, mp:2}, {qty:1, mp:2, mv:2}];
    const columns = [{id:"qty",Header:'Quantity'}, {id:"mv",Header:'Market Value'}, {id:"mp",Header:'Market Price'}]
    

    The above code returns:

    [ { Quantity: 1, 'Market Price': 2 },
      { Quantity: 1, 'Market Price': 2, 'Market Value': 2 } ]
    

    Hope this helps!