[英]How do I copy only the Objects from Array to another Array using .splice() method?
我有一个如下所示的数组,并使用.localeCompare
方法对其进行排序。 排序完成后,我想提升 Array 中的children
项为 true 的项。
可以参考这个jsfiddle的代码: https://jsfiddle.net/sarav4gs/npd2mchs/78/
var data = [
{
"item": "aaabb110",
"recID": 15
},
{
"item": "aaabbbccc1",
"recID": 16
},
{
"item": "ZTemplate 1",
"recID": null,
"children": [
{
"item": "zaa",
"recID": 70
},
{
"item": "Qualification 1",
"recID": 73
}]
},
{
"item": "bbaacc1",
"recID": 17
},
{
"item": "bbaa005",
"recID": 18
},
{
"item": "ATemplate 2",
"recID": null,
"children": [{
"item": "Qualification 1",
"recID": 83
},
{
"item": "Qualification 2",
"recID": 84
},
{
"item": "Custom",
"recID": 86
},
{
"item": "custom code",
"recID": 87
},
{
"item": "aaa",
"recID": 89
}
]
}
];
为了实现这一点,我正在尝试对具有子项的项目进行切片并将其复制到一个新数组中,然后将其推送到顶部的同一个数组中。 (我尝试使用.splice,.unshift),但在 output 中,它在第一个参数中复制完整的数组,而不是作为对象。
var CQTemplates = [];
var newData = data.filter(function(item,i){
if(item.children){
var removeAt = data.indexOf(item);
var CQTemplateCodeItem = data.slice(removeAt, removeAt+1);
pushAt = CQTemplates.length;
CQTemplates[pushAt] = CQTemplateCodeItem[0];
}
return item.children == undefined;
})
预期的 Output 是这样的
Array [
"itemsWithChildifAny? - sorted",
"itemsWithChildifAny? - sorted",
"Item - sorted",
"Item - sorted",
"Item - sorted"
]
您正在尝试将有孩子和没有孩子的对象分开。 你可以试试这个
var CQTemplates = [];
let withChildren = [];
let withoutChildren = [];
data.forEach(function(item){
if(item.children){
withChildren.push(item);
} else {
withoutChildren.push(item);
}
})
var withoutChildren = [];
var withChildren = data.filter(function(item,i){
if(!item.children){
withoutChildren.push(item);
return false;
}
return true;
})
console.log('Combined array', [...withChildren, ...withoutChildren]);
Output 会像
编码快乐!!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.