0

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

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
craig
  • 571
  • 2
  • 4
  • 13
  • Have a look here: http://stackoverflow.com/questions/7015512/removing-an-element-from-an-array-specifying-a-value-in-javascript?rq=1 – ChrisSwires Jan 24 '14 at 10:36

3 Answers3

3

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/

georg
  • 211,518
  • 52
  • 313
  • 390
2

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).

roland
  • 7,695
  • 6
  • 46
  • 61
2

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;
}
Guffa
  • 687,336
  • 108
  • 737
  • 1,005