JavaScript:如何获取以特定字符串开头的对象的所有键和值? [英] JavaScript: How can I get all the keys and values of an object that begin with a specific string?
问题描述
我试图获取以 imageIds
开头的对象的所有键和值。
I am trying to get all the keys and values of an object that begin with imageIds
.
My对象显示如下:
{
title: 'fsdfsd',
titleZh: 'fsdfsd',
body: 'fsdf',
bodyZh: 'sdfsdf',
imageIds: '/uploads/tmp/image-3.png',
imageIdsZh: ''
}
但我只需要属性 imageIds
和 imageIdsZh
。但是明天,一个对象可能包含 imageIdsBlah
,我也需要把它拿起来。我可以从对象中删除前几个属性,但是下一个对象可能包含其他属性,例如 foo:'bar'
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'
推荐答案
一些功能风格很棒:
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);
演示: http://jsfiddle.net/ngX4m/
一些小解释:
- 我们使用
Array.prototype.filter()
函数来过滤出以`imageIds2 开头的键 - 我们使用
Array.prototype.reduce()
将过滤后的密钥数组转换为key-value
对。为此我们使用{}
的初始值(一个空对象),填写它并从每个执行步骤返回。
- We use
Array.prototype.filter()
function to filter out the keys that start with `imageIds2 - We use
Array.prototype.reduce()
to convert an array of filtered keys into an object ofkey-value
pairs. For that we use the initial value of{}
(an empty object), fill it and return from every execution step.
UPD :
来自 @ GitaarLAB :
Object.keys
是ES5,但返回一个对象自己的属性(因此不需要obj.hasOwnProperty(key)
)
Object.keys
is ES5, but returns an objects own properties (so no need forobj.hasOwnProperty(key)
)
这篇关于JavaScript:如何获取以特定字符串开头的对象的所有键和值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!