Question

I have the following array:

KHWArray = [{"date":"23 Jan 14","hours":12,"mins":"31","score":22},
           {"date":"23 Jan 14","hours":12,"mins":"36","score":22},
           {"date":"23 Jan 14","hours":12,"mins":"44","score":22}
           ]

How can I go about deleting the hours and mins sections from all arrays so I am just left with date and score.

I have looked into splicing and delete but can't seem to make this work

Was it helpful?

Solution

Your array elements are objects, not arrays and there's no built-in function to slice objects. It's easy to write though:

function removeKeys(obj, keys) {
    keys.forEach(function(key) { delete obj[key] });
    return obj
}

and then

KHWArray = KHWArray.map(function(elem) {
    return removeKeys(elem, ['hours', 'mins'])    
})

http://jsfiddle.net/HZDaX/

OTHER TIPS

map seems your best bet:

var result = KHWArray.map(function(elt) {
  return {date: elt.date, score: elt.score};
});

As an alternative use the versatile reduce:

var result = KHWArray.reduce(function(target, elt) {
  target.push({date: elt.date, score: elt.score});
  return target;
}, []);

Basically pass an empty array as the second argument; it will be referenced as target inside the handler. Push an object that fits your needs and return your target.

Caution: map and reduce are both part of the ECMAScript 5th edition. Ensure your targeted browsers support it (or provide a shim).

Use the delete operator to delete properties from an object:

for (var i = 0; i < KHWArray.length; i++) {
  delete KHWArray[i].hours;
  delete KHWArray[i].mins;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top