0

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;
      }
    )
  );
1
  • 1
    forEach is not meant to return anything. In fact, it doesn't return obj. If you're planning to alter the row object, you should not map it. map method is meant to be used with a return statement. Commented May 15, 2020 at 15:30

1 Answer 1

1

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!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.