1

I have an array of objects, like so:

arr = [{"timeslot":"6am7am","AVG(Monday)":10,"AVG(Tuesday)":11,"AVG(Wednesday)":7}] 

Each object will always contain the "timeslot" property, and can contain any combination of the day-of-the-week properties, Monday through Sunday. Each day of the week may only be represented once in a single object.

I want to alter each object: specifically, the key names of the day-of-the-week properties only (the "timeslot" property will be unchanged"), to get an array like so:

newArr = [{"timeslot":"6am7am","Monday":10,"Tuesday":11,"Wednesday":7}] 

My slightly unreadable solution works:

// Iterate the array of objects results.forEach(function(o) { // Iterate the object's properties Object.keys(o).forEach(function(k) { if(k.includes("AVG")) { var len = k.length; var pos = len - 1; var newKey = k.slice(4, pos); // Extract the day of the week from the key name o[newKey] = o[k]; // Create the new property with the same value and the new key-name delete o[k]; // Delete the original property } }); }); 

How can I improve this solution?

1
  • 4
    You could just write o[k.slice(4, -1)] = o[k]. No need for all those intermediate variables. There is not much else that could be improved. Commented Jan 13, 2017 at 14:56

1 Answer 1

2

Instead of mutating the original array by adding and removing keys from each object, Array#map the array into a new array, and recreate the objects using Array#reduce:

var arr = [{"timeslot":"6am7am","AVG(Monday)":10,"AVG(Tuesday)":11,"AVG(Wednesday)":7}]; var result = arr.map(function(obj) { return Object.keys(obj).reduce(function(r, key) { var k = key.includes('AVG') ? key.slice(4, -1) : key; r[k] = obj[key]; return r; }, {}); }); console.log(result);

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.