我想知道是否有一些辅助JavaScript库具有类似于underscore.js的_.extend
的功能。
我正在寻找的是一个给出如下关联数组的函数:
{ foo: 1, bar: 2 }
和另一个“扩展”关联数组,如下所示:
{ foo : 3 }
可以轻松构建以下“增强”结构:
{ foo: [1, 3], bar: 2 }
否则我必须手动执行此操作,但此任务似乎足够通用,可以成为某些辅助库中的函数。
通过示例说明不同对象应该发生的情况:
基础对象:{ foo: 1, bar: 2 }
扩展对象:{ quuz: 3, bar: 4 }
结果:{ foo: 1, bar: [2, 4], quuz: 3 }
实际上,现在我很清楚该操作是可交换的(基数和扩展可以切换,结果始终相同)
其他示例:
基础对象:{ foo: 1, bar: [2,5] }
扩展对象:{ foo: {a: 'A', b: 'B'} , bar: 4 }
结果:{ foo: [1, {a: 'A', b: 'B'}], bar: [2, 4, 5], quuz: 3 }
最佳答案
您的需求不是很清楚,您希望不同的对象发生什么?但是,这是一个浅层扩展,可以满足您的要求,或者将其用作实验的基础并将其调整到您的设计中。
Javascript
function curstomExtend(target) {
var typeTarget = typeof target;
if (target === null || typeTarget !== 'object' && typeTarget !== 'function') {
throw new TypeError('target');
}
Array.prototype.slice.call(arguments, 1).forEach(function (source) {
var typeSource = typeof source;
if (source === null || typeSource !== 'object' && typeSource !== 'function') {
throw new TypeError('source');
}
Object.keys(source).forEach(function (key) {
var temp;
if (target.hasOwnProperty(key)) {
if (Array.isArray(target[key])) {
target[key].push(source[key]);
} else {
target[key] = [target[key]];
target[key].push(source[key]);
}
} else {
target[key] = source[key];
}
});
});
return target;
};
var a = {
foo: 1,
bar: 2,
fy: {
a: 1,
b: 2
}
},
b = {
foo: 3,
fy: {
s: 3,
t: 4
}
},
c = {
foo: [4, 5]
},
d = {
foo: {
x: 4,
y: 5
},
fy: {
s: 5,
t: 6
}
};
curstomExtend(a, b, c, d);
console.log(JSON.stringify(a));
输出
{"foo":[1,3,[4,5],{"x":4,"y":5}],"bar":2,"fy":[{"a":1,"b":2},{"s":3,"t":4},{"s":5,"t":6}]}
关于jsFiddle
关于javascript - 寻找一个函数来执行比 underscore.js 扩展函数更复杂的工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22113750/