Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
195
rated 0 times [  200] [ 5]  / answers: 1 / hits: 10996  / 11 Years ago, tue, december 10, 2013, 12:00:00

I am trying to get all the keys and values of an object that begin with imageIds.



My object appears as the following:



{
title: 'fsdfsd',
titleZh: 'fsdfsd',
body: 'fsdf',
bodyZh: 'sdfsdf',
imageIds: '/uploads/tmp/image-3.png',
imageIdsZh: ''
}


but I only need the properties imageIds, and imageIdsZh. However tomorrow, a object might contain imageIdsBlah and I would need to pick it up as well. I could remove the first few properties from the object, but then the next object might contain additional properties such as foo: 'bar'


More From » javascript

 Answers
3

Some functional style awesomeness:




var data = {
title: 'fsdfsd',
titleZh: 'fsdfsd',
body: 'fsdf',
bodyZh: 'sdfsdf',
imageIds: '/uploads/tmp/image-3.png',
imageIdsZh: ''
};

var z = Object.keys(data).filter(function(k) {
return k.indexOf('imageIds') == 0;
}).reduce(function(newData, k) {
newData[k] = data[k];
return newData;
}, {});

console.log(z);




Demo: http://jsfiddle.net/ngX4m/


Some minor explanation:



  1. We use Array.prototype.filter() function to filter out the keys that start with `imageIds2

  2. We use Array.prototype.reduce() to convert an array of filtered keys into an object of key-value pairs. For that we use the initial value of {} (an empty object), fill it and return from every execution step.


UPD:


A fair update from @GitaarLAB:



Object.keys is ES5, but returns an objects own properties (so no need for obj.hasOwnProperty(key))



[#49689] Monday, December 9, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
giovanny

Total Points: 314
Total Questions: 101
Total Answers: 90

Location: Tajikistan
Member since Thu, Apr 14, 2022
2 Years ago
;