I am trying to get all the keys and values of an object that begin with imageIds
.
My object appears as the following:
{
title: \'fsd
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:
Array.prototype.filter()
function to filter out the keys that start with `imageIds2Array.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 forobj.hasOwnProperty(key)
)
// json to be searched
var data = {
title: 'fsdfsd',
titleZh: 'fsdfsd',
body: 'fsdf',
bodyZh: 'sdfsdf',
imageIds: '/uploads/tmp/image-3.png',
imageIdsZh: ''
};
// takes the json 'data' as its 1st parameter
// and the desired 'property' to be searched as the 2nd parameter
// for loop iterates through the entire json
// if the property parameter matches a 'key' name in json e.g. 'imageIds'
// then the value for that property is returned
function fetchProperty (data, property) {
for(var key in data) {
if(key === property) {
return data[key];
}
}
}
// if you wanted to return a bunch of data according to a particular key - value pair
// you could do something like this...
// assume 'array' contains a bunch of jsons
// newData will hold jsons containing your newly fetched data points
function fetchNewData() {
var newData = [];
for(var i = 0; i < array.length; i++) {
var value1 = fetchProperty(array[i], 'imageIds');
var value2 = fetchProperty(array[i], 'imageIdsZh');
var value3 = fetchProperty(array[i], 'imageIdsBlah');
var tempJSON = {};
tempJSON.imageIds = value1;
tempJSON.imageIdsZh = value2;
tempJSON.imageIdsBlah = value3;
newData.push(tempJSON);
}
return newData;
}
** I hope this was helpful. If you have any further questions, feel free to reach out. Best of luck. **
Along the lines of the answer from @zerkms, I've been working on a functional programming library for Javascript. With the tools from that library, this turns into a (somewhat dense) one-liner:
var data = {
title: 'fsdfsd',
titleZh: 'fsdfsd',
body: 'fsdf',
bodyZh: 'sdfsdf',
imageIds: '/uploads/tmp/image-3.png',
imageIdsZh: ''
};
var x = pick(filter(compose(eq("imageIds"), substring(0,8)), keys(data)), data);
console.log(x);
This code is not necessarily any better than what @zerkms posted, but it does show off some more of the power of functional abstractions beyond the few that are built into Array.prototype
.
You can see it in action on JSFiddle.
Depending on how large the object is, this may not scale well, but it will work
for(key in obj){
if(obj.hasOwnProperty(key)){
if(key.indexOf("imageIds")===0){
//do something
}
}
}
One also needs to use hasOwnProperty
in conjunction with the for-in loop (not mentioned in most current previous answers).
Reason is that the for-in loop will also go over the methods/properties that an object would inherit from the proto-type chain (should someone or some library have added custom stuff).
So you are looking for something simple and reliable like this:
function fetch(obj, str){
var key, results = [];
for(key in obj) obj.hasOwnProperty(key)
&& key.indexOf(str) === 0
&& results.push([ key, obj[key] ]);
return results;
}
Note: you could also name this function 'getAllKeysAndValuesStartingWith' (or gakavsw should you work for the army haha).
Usage:
fetch(object, string)
returns a simple (to loop over) array with found results,
so var my_results = fetch(testObj, 'imageId');
would give the following output:
[ //array of arrays
['imageIds', '/uploads/tmp/image-3.png']
, ['imageIdsZh', ''] /*
, [key, value] and more if it finds them */
]
Working jsfiddle here.
Naturally one could also push just the values: results.push(obj[key])
I would recommend against returning an object ( (results[key]=obj[key])
) since the array is easier to work with in this case.
Hope this helps!