本文翻译自:How to get a subset of a javascript object's properties
Say I have an object: 说我有一个对象:
elmo = {
color: 'red',
annoying: true,
height: 'unknown',
meta: { one: '1', two: '2'}
};
I want to make a new object with a subset of its properties. 我想用其属性的子集创建一个新对象。
// pseudo code
subset = elmo.slice('color', 'height')
//=> { color: 'red', height: 'unknown' }
How may I achieve this? 我该如何实现?
参考:https://stackoom.com/question/1Cblw/如何获取javascript对象属性的子集
There is nothing like that built-in to the core library, but you can use object destructuring to do it... 核心库中没有内置的东西,但是您可以使用对象分解来实现。
const {color, height} = sourceObject;
const newObject = {color, height};
You could also write a utility function do it... 您也可以编写一个实用程序函数来做...
const cloneAndPluck = function(sourceObject, keys) {
const newObject = {};
keys.forEach((obj, key) => { newObject[key] = sourceObject[key]; });
return newObject;
};
const subset = cloneAndPluck(elmo, ["color", "height"]);
Libraries such as Lodash also have _.pick()
. Lodash等库也具有_.pick()
。
How about: 怎么样:
function sliceObj(obj) {
var o = {}
, keys = [].slice.call(arguments, 1);
for (var i=0; i
I suggest taking a look at Lodash ; 我建议看一看Lodash ; it has a lot of great utility functions. 它具有许多强大的实用程序功能。
For example pick()
would be exactly what you seek: 例如pick()
正是您要寻找的:
var subset = _.pick(elmo, ['color', 'height']);
fiddle 小提琴
function splice()
{
var ret = new Object();
for(i = 1; i < arguments.length; i++)
ret[arguments[i]] = arguments[0][arguments[i]];
return ret;
}
var answer = splice(elmo, "color", "height");
Note: though the original question asked was for javascript, it can be done jQuery by below solution 注意:尽管最初提出的问题是针对javascript的,但可以通过以下解决方案完成jQuery
you can extend jquery if you want here is the sample code for one slice: 您可以扩展jquery,如果您想获得一个切片的示例代码:
jQuery.extend({
sliceMe: function(obj, str) {
var returnJsonObj = null;
$.each( obj, function(name, value){
alert("name: "+name+", value: "+value);
if(name==str){
returnJsonObj = JSON.stringify("{"+name+":"+value+"}");
}
});
return returnJsonObj;
}
});
var elmo = {
color: 'red',
annoying: true,
height: 'unknown',
meta: { one: '1', two: '2'}
};
var temp = $.sliceMe(elmo,"color");
alert(JSON.stringify(temp));
here is the fiddle for same: http://jsfiddle.net/w633z/ 这是相同的小提琴: http : //jsfiddle.net/w633z/