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

1

3 Answers 3

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/

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

1 Comment

Note: The map method does not exist in older browsers, for example IE8.
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).

Comments

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;
}

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.