Javascript 递归扩展Jquery对象
我试图以一种可重复的方式扩展javascript对象,而不必过多地迭代我的元素。这是一个非常简单的例子来说明这个问题:Javascript 递归扩展Jquery对象,javascript,jquery,Javascript,Jquery,我试图以一种可重复的方式扩展javascript对象,而不必过多地迭代我的元素。这是一个非常简单的例子来说明这个问题: var test1 = [ { tests: [ { label: "this is a test" }, { label: "this is a test"
var test1 = [
{
tests: [
{
label: "this is a test"
},
{
label: "this is a test"
},
{
label: "this is a test"
}
]}];
var test2 = [
{
tests: [
{comments: 'this is a comment'}
]}];
console.log($.extend(true, test1, test2))
注释项现在的工作方式将只应用于test1中的第一个元素。我想知道是否有一个巧妙的方法来做到这一点,这样它适用于所有人,而不必做每一件事。显然,在这个小例子中,forEach是可以的,但在我的实际示例中,我有一个非常深的对象,其中有几个列表,我希望将这些列表与每个项目的静态数据合并。有没有什么很酷的工具可以让这变得简单
var idealResult = [
{
tests: [
{
label: "this is a test",
comments: 'this is a comment'
},
{
label: "this is a test",
comments: 'this is a comment'
},
{
label: "this is a test",
comments: 'this is a comment'
}
]}];
像这样
也许你会在这里找到一些有用的东西:我尝试过使用递归算法,看到了吗
函数递归附加(src,dest){
//如果是数组,则循环遍历元素
如果($.isArray(src)){
对于(变量i=0;i
该算法假设您的src
和dest
具有相同的结构(无论它是什么),直到最深层,其中dest
将由类似于src
的单个对象的对象数组组成
在找到第一个非数组/非对象键后,它也会停止
它还没有完全测试过,所以抛出大量随机测试用例!您需要添加针对不同结构的src
和dest
的保护(我总是假设会有相应的src[I]
,dest[I]
或src[key]
,dest[key]
)
希望这为您指明了正确的方向=)您必须自己进行克隆。您可以使用Object.create()或类似OOP的继承,或者您可以一次迭代和固定这无疑让我走上了正确的道路,谢谢。我可以相信这样一个事实:数组将具有相同的结构,因此没有问题。@Korra没有问题,只是确保测试许多不同的情况!此外,如果答案对您有效,请接受它;)
console.log(test1.concat(test2))
function recursiveAppend(src, dest) {
// If it's an array, loop through elements
if ($.isArray(src)) {
for (var i = 0; i < src.length; i++) {
// If function returns true, then it found the 'deepest' level...
if ( recursiveAppend(src[i], dest[i]) ) {
// ...so extend all objects in the destination...
for (var j = 0; j < dest.length; j++) {
$.extend(true, dest[j], src[i]);
}
// ...and stop looping
break;
}
}
}
// If it's an object, loop through keys
else if ($.isPlainObject(src)) {
for (var key in src) {
if (src.hasOwnProperty(key)) {
// Check if the destination has the key
if (dest.hasOwnProperty(key)) {
return recursiveAppend(src[key], dest[key])
}
// If it doesn't, then we found the 'deepest' level
else {
//debugger;
return true;
}
}
}
}
else {
//debugger;
return true;
}
};