JavaScript:如何获取以特定字符串开头的对象的所有键和值? [英] JavaScript: How can I get all the keys and values of an object that begin with a specific string?

查看:74
本文介绍了JavaScript:如何获取以特定字符串开头的对象的所有键和值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图获取以 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/

一些小解释:


  1. 我们使用 Array.prototype.filter()函数来过滤出以`imageIds2
  2. 开头的键
  3. 我们使用 Array.prototype.reduce()将过滤后的密钥数组转换为 key-value 对。为此我们使用 {} 的初始值(一个空对象),填写它并从每个执行步骤返回。

  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

来自 @ GitaarLAB


Object.keys 是ES5,但返回一个对象自己的属性(因此不需要 obj.hasOwnProperty(key)

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

这篇关于JavaScript:如何获取以特定字符串开头的对象的所有键和值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆