Related
So I have the following JSON array
[
{
"characterID": 0,
"description": "Series 1",
"id": 1,
"seriesID": 0,
"status": "ACCEPTED",
"type": "SERIES",
"userID": 1
},
{
"characterID": 0,
"description": "Series 2",
"id": 2,
"seriesID": 0,
"status": "ACCEPTED",
"type": "SERIES",
"userID": 1
},
{
"characterID": 0,
"description": "Character 1",
"id": 1,
"seriesID": 25,
"status": "ACCEPTED",
"type": "CHARACTER",
"userID": 1
},
{
"URL": "https://previews.123rf.com/images/aquir/aquir1311/aquir131100316/23569861-sample-grunge-red-round-stamp.jpg",
"characterID": 853,
"description": "Picture 1",
"id": 1,
"seriesID": 25,
"status": "ACCEPTED",
"type": "IMAGE",
"userID": 1
},
{
"URL": "https://c.tenor.com/uEjQxCwAWfgAAAAC/sample.gif",
"characterID": 1,
"description": "Gif 1",
"id": 1,
"seriesID": 1,
"status": "ACCEPTED",
"type": "GIF",
"userID": 1
},
{
"characterID": 0,
"description": "Idea 1",
"id": 1,
"seriesID": 0,
"status": "ACCEPTED",
"type": "IDEA",
"userID": 1
}
]
However I want to achieve splitting the arrays as follows
[
{
"characterID": 0,
"description": "Series 1",
"id": 1,
"seriesID": 0,
"status": "ACCEPTED",
"type": "SERIES",
"userID": 1
},
{
"characterID": 0,
"description": "Series 2",
"id": 2,
"seriesID": 0,
"status": "ACCEPTED",
"type": "SERIES",
"userID": 1
}
]
[
{
"characterID": 0,
"description": "Character 1",
"id": 1,
"seriesID": 25,
"status": "ACCEPTED",
"type": "CHARACTER",
"userID": 1
}
]
What I want to achieve is split the JSON in segments based on what type it contains within the array.
I am working in Javascript / Vue, if there's any solutions for this, would be appreciated.
Array.reduce, will work nicely here.
Below is an example.
var data = JSON.parse('[{"characterID":0,"description":"Series 1","id":1,"seriesID":0,"status":"ACCEPTED","type":"SERIES","userID":1},{"characterID":0,"description":"Series 2","id":2,"seriesID":0,"status":"ACCEPTED","type":"SERIES","userID":1},{"characterID":0,"description":"Character 1","id":1,"seriesID":25,"status":"ACCEPTED","type":"CHARACTER","userID":1},{"URL":"https://previews.123rf.com/images/aquir/aquir1311/aquir131100316/23569861-sample-grunge-red-round-stamp.jpg","characterID":853,"description":"Picture 1","id":1,"seriesID":25,"status":"ACCEPTED","type":"IMAGE","userID":1},{"URL":"https://c.tenor.com/uEjQxCwAWfgAAAAC/sample.gif","characterID":1,"description":"Gif 1","id":1,"seriesID":1,"status":"ACCEPTED","type":"GIF","userID":1},{"characterID":0,"description":"Idea 1","id":1,"seriesID":0,"status":"ACCEPTED","type":"IDEA","userID":1}]');
const grouped = data.reduce((a, v) => {
if (!a[v.type]) a[v.type] = [];
a[v.type].push(v);
return a;
}, {});
console.log(grouped);
You can use reduce to create a new object with type as keys:
var res = data.reduce((acc, val) => {
if (!acc[val.type]) {
acc[val.type] = [val];
} else {
acc[val.type].push(val)
}
return acc;
}, {})
The result will look something like:
{
"SERIES":[
{
"characterID":0,
"description":"Series 1",
"id":1,
"seriesID":0,
"status":"ACCEPTED",
"type":"SERIES",
"userID":1
},
{
"characterID":0,
"description":"Series 2",
"id":2,
"seriesID":0,
"status":"ACCEPTED",
"type":"SERIES",
"userID":1
}
],
"CHARACTER":[
{
"characterID":0,
"description":"Character 1",
"id":1,
"seriesID":25,
"status":"ACCEPTED",
"type":"CHARACTER",
"userID":1
}
],
"IMAGE":[
{
"URL":"https://previews.123rf.com/images/aquir/aquir1311/aquir131100316/23569861-sample-grunge-red-round-stamp.jpg",
"characterID":853,
"description":"Picture 1",
"id":1,
"seriesID":25,
"status":"ACCEPTED",
"type":"IMAGE",
"userID":1
}
],
"GIF":[
{
"URL":"https://c.tenor.com/uEjQxCwAWfgAAAAC/sample.gif",
"characterID":1,
"description":"Gif 1",
"id":1,
"seriesID":1,
"status":"ACCEPTED",
"type":"GIF",
"userID":1
}
],
"IDEA":[
{
"characterID":0,
"description":"Idea 1",
"id":1,
"seriesID":0,
"status":"ACCEPTED",
"type":"IDEA",
"userID":1
}
]
}
I am not sure if you want to split and store into separate arrays or not but, if thats the case you can try this:
const obj = [
{
"characterID": 0,
"description": "Series 1",
"id": 1,
"seriesID": 0,
"status": "ACCEPTED",
"type": "SERIES",
"userID": 1
},
{
"characterID": 0,
"description": "Series 2",
"id": 2,
"seriesID": 0,
"status": "ACCEPTED",
"type": "SERIES",
"userID": 1
},
{
"characterID": 0,
"description": "Character 1",
"id": 1,
"seriesID": 25,
"status": "ACCEPTED",
"type": "CHARACTER",
"userID": 1
},
{
"URL": "https://previews.123rf.com/images/aquir/aquir1311/aquir131100316/23569861-sample-grunge-red-round-stamp.jpg",
"characterID": 853,
"description": "Picture 1",
"id": 1,
"seriesID": 25,
"status": "ACCEPTED",
"type": "IMAGE",
"userID": 1
},
{
"URL": "https://c.tenor.com/uEjQxCwAWfgAAAAC/sample.gif",
"characterID": 1,
"description": "Gif 1",
"id": 1,
"seriesID": 1,
"status": "ACCEPTED",
"type": "GIF",
"userID": 1
},
{
"characterID": 0,
"description": "Idea 1",
"id": 1,
"seriesID": 0,
"status": "ACCEPTED",
"type": "IDEA",
"userID": 1
}
];
const seriesTypeObjs = [];
obj.map(eachObj => {
if (eachObj.type === 'SERIES'){
seriesTypeObjs.push(eachObj);
}
});
console.log('Series Type Objs =>', seriesTypeObjs);
You can use the same code to test for other type values too.
The easiest way is using a utility library like lodash
Specifically method groupBy
_.groupBy(data, 'type');// {SERIES: Array(2), CHARACTER: Array(1), IMAGE: Array(1), GIF: Array(1), IDEA: Array(1)}
UPDATE:(vanilla approach without any libraries)
Solution Using The Map which is object holds key-value pairs key is the type and value is their entry group of that type with ?. Optional chaining and ?? Nullish coalescing operator
let map = new Map()
for(entry of data){
const type = entry?.type ?? "untyped";
map.set(type, [...map.get(type)??[],entry])
}
// Map(5) {'SERIES' => Array(2), 'CHARACTER' => Array(1), 'IMAGE' => Array(1), 'GIF' => Array(1), 'IDEA' => Array(1)}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
[{
"id": "5f283e239b81681618b19b5d",
"listItemId": 3,
"formData": {
"name": "הבית שלנו בחיפה ",
"address": "הגולן 150",
"geo": "ישראל",
"currency": "NIS",
"productPrice": "150000",
"expectedRevenue": "6955"
},
"productId": 1,
"formId": 1,
"createdAt": "2020-08-03T16:41:07.691Z",
"updatedAt": "2020-08-03T16:42:49.407Z",
"summary": {
"appreciationPer": 0,
"sumYieldPer": 0,
"portfolioPer": 0.022,
"worth": {
"currency": "ILS",
"value": 150000
},
"yieldPer": 0
}
}, {
"id": "5f283e499b81681618b19b5e",
"listItemId": 4,
"formData": {
"name": "הבית שלנו בארהבב",
"address": "רבי מלוביץת 10",
"geo": "ארהב",
"currency": "USD",
"productPrice": "1500000",
"expectedRevenue": "699"
},
"productId": 1,
"formId": 1,
"createdAt": "2020-08-03T16:41:45.317Z",
"updatedAt": "2020-08-03T16:41:45.317Z",
"summary": {
"appreciationPer": 0,
"sumYieldPer": 0,
"portfolioPer": 0.761,
"worth": {
"currency": "ILS",
"value": 5261700
},
"yieldPer": 0
}
}, {
"id": "5f283e699b81681618b19b5f",
"listItemId": 5,
"formData": {
"name": "דירהב אירופה",
"address": "אירוהפם 2",
"geo": "אירופה",
"currency": "NIS",
"productPrice": "1500000",
"expectedRevenue": "6000"
},
"productId": 1,
"formId": 1,
"createdAt": "2020-08-03T16:42:17.087Z",
"updatedAt": "2020-08-03T16:42:17.087Z",
"summary": {
"appreciationPer": 0,
"sumYieldPer": 0,
"portfolioPer": 0.761,
"worth": {
"currency": "ILS",
"value": 5261700
},
"yieldPer": 0
}
}]
hey, how to Map this array to get a calculated sum of all the summry.worth.value property in side each object...
can someone pls help me figure how to do it?
Use Array.prototype.reduce().
The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in single output value.
var total = array.reduce((accumulator, current_value)=> {
return accumulator + current_value.summary.worth.value;
}, 0);
Example:
var array = [{
"id": "5f283e239b81681618b19b5d",
"listItemId": 3,
"formData": {
"name": "הבית שלנו בחיפה ",
"address": "הגולן 150",
"geo": "ישראל",
"currency": "NIS",
"productPrice": "150000",
"expectedRevenue": "6955"
},
"productId": 1,
"formId": 1,
"createdAt": "2020-08-03T16:41:07.691Z",
"updatedAt": "2020-08-03T16:42:49.407Z",
"summary": {
"appreciationPer": 0,
"sumYieldPer": 0,
"portfolioPer": 0.022,
"worth": {
"currency": "ILS",
"value": 150000
},
"yieldPer": 0
}
},
{
"id": "5f283e499b81681618b19b5e",
"listItemId": 4,
"formData": {
"name": "הבית שלנו בארהבב",
"address": "רבי מלוביץת 10",
"geo": "ארהב",
"currency": "USD",
"productPrice": "1500000",
"expectedRevenue": "699"
},
"productId": 1,
"formId": 1,
"createdAt": "2020-08-03T16:41:45.317Z",
"updatedAt": "2020-08-03T16:41:45.317Z",
"summary": {
"appreciationPer": 0,
"sumYieldPer": 0,
"portfolioPer": 0.761,
"worth": {
"currency": "ILS",
"value": 5261700
},
"yieldPer": 0
}
},
{
"id": "5f283e699b81681618b19b5f",
"listItemId": 5,
"formData": {
"name": "דירהב אירופה",
"address": "אירוהפם 2",
"geo": "אירופה",
"currency": "NIS",
"productPrice": "1500000",
"expectedRevenue": "6000"
},
"productId": 1,
"formId": 1,
"createdAt": "2020-08-03T16:42:17.087Z",
"updatedAt": "2020-08-03T16:42:17.087Z",
"summary": {
"appreciationPer": 0,
"sumYieldPer": 0,
"portfolioPer": 0.761,
"worth": {
"currency": "ILS",
"value": 5261700
},
"yieldPer": 0
}
}
];
var total = array.reduce((accumulator, current)=> accumulator+current.summary.worth.value, 0);
console.log(total);
I am unable to push childEntries into parent based on parentId using JS. Actually I need to populate the data into a tree view table.
Here is the JSON I got from API
[{
"displayName": "",
"order": 1,
"status": "Active",
"description": "Application Top Section",
"createDate": "2020-01-01 12:00:00",
"parentId": 0,
"modifiedDate": "2020-01-01 12:00:00",
"id": 0,
"type": "section"
}, {
"displayName": "",
"order": 1,
"status": "Active",
"description": "Application Side Navigation Section",
"createDate": "2020-01-01 12:00:00",
"parentId": 1,
"modifiedDate": "2020-01-01 12:00:00",
"id": 1,
"type": "section"
}, {
"displayName": "Puente Dashboard",
"order": 1,
"status": "Active",
"description": "Application Dashboard",
"createDate": "2020-01-01 12:00:00",
"parentId": 1,
"modifiedDate": "2020-01-01 12:00:00",
"id": 2,
"type": "link"
}, {
"displayName": "Security",
"order": 2,
"status": "Active",
"description": "Security Management",
"createDate": "2020-01-01 12:00:00",
"parentId": 1,
"modifiedDate": "2020-01-01 12:00:00",
"id": 3,
"type": "link"
}, {
"displayName": "User",
"order": 1,
"status": "Active",
"description": "User Management",
"createDate": "2020-01-01 12:00:00",
"parentId": 3,
"modifiedDate": "2020-01-01 12:00:00",
"id": 4,
"type": "link"
}, {
"displayName": "Role",
"order": 2,
"status": "Active",
"description": "Role Management",
"createDate": "2020-01-01 12:00:00",
"parentId": 3,
"modifiedDate": "2020-01-01 12:00:00",
"id": 5,
"type": "link"
}, {
"displayName": "Widget",
"order": 3,
"status": "Active",
"description": "Widget Management",
"createDate": "2020-01-01 12:00:00",
"parentId": 3,
"modifiedDate": "2020-01-01 12:00:00",
"id": 6,
"type": "link"
}]
And expected JSON is
[{
"displayName": "",
"order": 1,
"status": "Active",
"description": "Application Top Section",
"createDate": "2020-01-01 12:00:00",
"parentId": 0,
"modifiedDate": "2020-01-01 12:00:00",
"id": 0,
"type": "section"
},
{
"displayName": "",
"order": 1,
"status": "Active",
"description": "Application Side Navigation Section",
"createDate": "2020-01-01 12:00:00",
"parentId": 1,
"modifiedDate": "2020-01-01 12:00:00",
"id": 1,
"type": "section",
"childEntries": [{
"displayName": "Puente Dashboard",
"order": 1,
"status": "Active",
"description": "Application Dashboard",
"createDate": "2020-01-01 12:00:00",
"parentId": 1,
"modifiedDate": "2020-01-01 12:00:00",
"id": 2,
"type": "link"
},
{
"displayName": "Security",
"order": 2,
"status": "Active",
"description": "Security Management",
"createDate": "2020-01-01 12:00:00",
"parentId": 1,
"modifiedDate": "2020-01-01 12:00:00",
"id": 3,
"type": "link",
"childEntries": [{
"displayName": "User",
"order": 1,
"status": "Active",
"description": "User Management",
"createDate": "2020-01-01 12:00:00",
"parentId": 3,
"modifiedDate": "2020-01-01 12:00:00",
"id": 4,
"type": "link"
},
{
"displayName": "Role",
"order": 2,
"status": "Active",
"description": "Role Management",
"createDate": "2020-01-01 12:00:00",
"parentId": 3,
"modifiedDate": "2020-01-01 12:00:00",
"id": 5,
"type": "link"
},
{
"displayName": "Widget",
"order": 3,
"status": "Active",
"description": "Widget Management",
"createDate": "2020-01-01 12:00:00",
"parentId": 3,
"modifiedDate": "2020-01-01 12:00:00",
"id": 6,
"type": "link"
}
]
}
]
}
]
Using below code only I am able to add "kind","childEntries" and "expanded". But ultimately I am not getting my expected JSON.
this.widgetsource.forEach(function (element) { if(element.parentId == 1 || element.parentId == 0 ){ element.kind = "dir"; element.expanded = false; element.childEntries = []; }
Here in this.widgetsource I have stored the raw JSON.
Could you please help me here.
Thanks in advance.
You can check if its a child when parent is not equal to itself, then find the parent and add in child list.
const parsedObject = JSON.parse(`[{ "displayName": "", "order": 1, "status": "Active", "description": "Application Top Section", "createDate": "2020-01-01 12:00:00", "parentId": 0, "modifiedDate": "2020-01-01 12:00:00", "id": 0, "type": "section" }, { "displayName": "", "order": 1, "status": "Active", "description": "Application Side Navigation Section", "createDate": "2020-01-01 12:00:00", "parentId": 1, "modifiedDate": "2020-01-01 12:00:00", "id": 1, "type": "section" }, { "displayName": "Puente Dashboard", "order": 1, "status": "Active", "description": "Application Dashboard", "createDate": "2020-01-01 12:00:00", "parentId": 1, "modifiedDate": "2020-01-01 12:00:00", "id": 2, "type": "link" }, { "displayName": "Security", "order": 2, "status": "Active", "description": "Security Management", "createDate": "2020-01-01 12:00:00", "parentId": 1, "modifiedDate": "2020-01-01 12:00:00", "id": 3, "type": "link" }, { "displayName": "User", "order": 1, "status": "Active", "description": "User Management", "createDate": "2020-01-01 12:00:00", "parentId": 3, "modifiedDate": "2020-01-01 12:00:00", "id": 4, "type": "link" }, { "displayName": "Role", "order": 2, "status": "Active", "description": "Role Management", "createDate": "2020-01-01 12:00:00", "parentId": 3, "modifiedDate": "2020-01-01 12:00:00", "id": 5, "type": "link" }, { "displayName": "Widget", "order": 3, "status": "Active", "description": "Widget Management", "createDate": "2020-01-01 12:00:00", "parentId": 3, "modifiedDate": "2020-01-01 12:00:00", "id": 6, "type": "link" }]`);
/**
* converting into a map for efficient access by ID id:Object.
*/
const idMap = parsedObject.reduce((accum,obj)=>{
accum[obj.id] = obj;
return accum;
},{});
const categorisedList = [];
parsedObject.forEach(obj=>{
if(obj.parentId === obj.id){
categorisedList.push(obj);
}else{
const parent = idMap[obj.parentId];
if(!parent.childEntries){
parent.childEntries=[];
}
parent.childEntries.push(obj);
}
});
console.log(categorisedList);
//If you need as JSON String.
const json = JSON.stringify(categorisedList);
I have and object literal that is essentially a tree that does not have a fixed number of levels.
How can I search for a tree for a particular node, and then return this node with connection parameters when it is found in a spectacular javascript manner?
var data = [{
title: 'topNode',
id: 1,
children: [{
title: 'node1',
id: 2,
children: [{
title: 'randomNode_1',
id: 3,
},
{
title: 'node2',
id: 4,
children: [{
title: 'randomNode_2',
id: 5,
children: [{
title: 'node2',
id: 1111,
children: [{
title: 'randomNode_3',
id: 1232,
}]
}]
}]
}
]
}]
}];
tree build what should be done
tree built from api
serializeGoals: state => type => {
const _goals = JSON.parse(JSON.stringify(state.goals))
return {
title: 'Стратегия',
expand: true,
forst: true,
children: _goals.filter((item) => {
if (item.type !== null && type.some(typeID => typeID === item.type.id)) {
item.shadow = true
} else if (item.type !== null && type.length > 0) {
item.shadow = false
item.type.color = '#ECECEC'
}
item.children = _goals.filter((children) => {
if (children.parent_id === item.id) {
if (children.type !== null && type.some(typeID => typeID === children.type.id)) {
children.shadow = true
} else if (children.type !== null && type.length > 0) {
children.type.color = '#ECECEC'
children.shadow = false
}
return true
}
return false
})
return item.parent_id === null
})
}
}
Get api server JSON array
parent_id - element parent
[{
"id": 5,
"parent_id": null,
"responsible_id": null,
"type_id": 4,
"title": "Тестовая цель - 5",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 4, "title": "Персонал", "color": "#6190e8"}
}, {
"id": 7,
"parent_id": null,
"responsible_id": null,
"type_id": 4,
"title": "Тестовая цель - 7",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 4, "title": "Персонал", "color": "#6190e8"}
}, {
"id": 9,
"parent_id": null,
"responsible_id": null,
"type_id": 4,
"title": "Тестовая цель - 9",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 4, "title": "Персонал", "color": "#6190e8"}
}, {
"id": 11,
"parent_id": null,
"responsible_id": null,
"type_id": 3,
"title": "Тестовая цель - 11",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 3, "title": "Процессы", "color": "#13ce66"}
}, {
"id": 13,
"parent_id": null,
"responsible_id": null,
"type_id": 4,
"title": "Тестовая цель - 13",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 4, "title": "Персонал", "color": "#6190e8"}
}, {
"id": 15,
"parent_id": null,
"responsible_id": null,
"type_id": 2,
"title": "Тестовая цель - 15",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 2, "title": "Клиенты", "color": "#ff4949"}
}, {
"id": 17,
"parent_id": null,
"responsible_id": null,
"type_id": 4,
"title": "Тестовая цель - 17",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 4, "title": "Персонал", "color": "#6190e8"}
}, {
"id": 19,
"parent_id": null,
"responsible_id": null,
"type_id": 4,
"title": "Тестовая цель - 19",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 4, "title": "Персонал", "color": "#6190e8"}
}, {
"id": 20,
"parent_id": 11,
"responsible_id": null,
"type_id": 2,
"title": "Тестовая цель - 20",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 2, "title": "Клиенты", "color": "#ff4949"}
}, {
"id": 21,
"parent_id": null,
"responsible_id": null,
"type_id": 3,
"title": "Тестовая цель - 21",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 3, "title": "Процессы", "color": "#13ce66"}
}, {
"id": 23,
"parent_id": null,
"responsible_id": null,
"type_id": 2,
"title": "Тестовая цель - 23",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 2, "title": "Клиенты", "color": "#ff4949"}
}, {
"id": 25,
"parent_id": null,
"responsible_id": null,
"type_id": 1,
"title": "Тестовая цель - 25",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 1, "title": "Финансы", "color": "#ffc82c"}
}, {
"id": 26,
"parent_id": 15,
"responsible_id": null,
"type_id": 2,
"title": "Тестовая цель - 26",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 2, "title": "Клиенты", "color": "#ff4949"}
}, {
"id": 27,
"parent_id": null,
"responsible_id": null,
"type_id": 1,
"title": "Тестовая цель - 27",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 1, "title": "Финансы", "color": "#ffc82c"}
}, {
"id": 28,
"parent_id": 7,
"responsible_id": null,
"type_id": 2,
"title": "Тестовая цель - 28",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 2, "title": "Клиенты", "color": "#ff4949"}
}, {
"id": 29,
"parent_id": null,
"responsible_id": null,
"type_id": 4,
"title": "Тестовая цель - 29",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 4, "title": "Персонал", "color": "#6190e8"}
}, {
"id": 31,
"parent_id": null,
"responsible_id": null,
"type_id": 2,
"title": "Тестовая цель - 31",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 2, "title": "Клиенты", "color": "#ff4949"}
}, {
"id": 33,
"parent_id": null,
"responsible_id": null,
"type_id": 3,
"title": "Тестовая цель - 33",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 3, "title": "Процессы", "color": "#13ce66"}
}, {
"id": 34,
"parent_id": 31,
"responsible_id": null,
"type_id": 4,
"title": "Тестовая цель - 34",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 4, "title": "Персонал", "color": "#6190e8"}
}, {
"id": 35,
"parent_id": null,
"responsible_id": null,
"type_id": 1,
"title": "Тестовая цель - 35",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 1, "title": "Финансы", "color": "#ffc82c"}
}, {
"id": 36,
"parent_id": 34,
"responsible_id": null,
"type_id": 1,
"title": "Тестовая цель - 36",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 1, "title": "Финансы", "color": "#ffc82c"}
}, {
"id": 37,
"parent_id": null,
"responsible_id": null,
"type_id": 4,
"title": "Тестовая цель - 37",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 4, "title": "Персонал", "color": "#6190e8"}
}, {
"id": 39,
"parent_id": null,
"responsible_id": null,
"type_id": 3,
"title": "Тестовая цель - 39",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 3, "title": "Процессы", "color": "#13ce66"}
}, {
"id": 40,
"parent_id": 34,
"responsible_id": null,
"type_id": 2,
"title": "Тестовая цель - 40",
"description": null,
"period": 2018,
"weight": null,
"responsible": null,
"type": {"id": 2, "title": "Клиенты", "color": "#ff4949"}
}]
I would use a recursive function to iterate through the tree and return the node when the expected one is found (I assumed the title is the search criteria) or return null if none was found.
In example :
var data = [
{
title: 'topNode',
id: 1,
children: [
{
title: 'node1',
id: 2,
children: [
{
title: 'randomNode_1',
id: 3,
},
{
title: 'node2',
id: 4,
children: [
{
title: 'randomNode_2',
id: 5,
children: [
{
title: 'node2',
id: 1111,
children: [
{
title: 'randomNode_3',
id: 1232,
}]
}]
}]
}]
}]
}];
function FindSpecificData(node, titleToFind)
{
let newNode = null;
for (let i = 0; i < node.length; ++i)
{
if (node[i].title == titleToFind)
newNode = node[i];
else if ('children' in node[i])
newNode = FindSpecificData(node[i].children, titleToFind);
if (newNode != null)
return (newNode);
}
return (null);
}
console.log(FindSpecificData(data, 'randomNode_2'));
console.log(FindSpecificData(data, 'randomNode_1'));
console.log(FindSpecificData(data, 'missing node'));
Try this simple method to find out your node
function getNode(node) {
if (node.title === 'randomNode_3') {
return true;
} else if (!node.children && !node.id) {
return false;
} else {
if (node.children) {
for (var i = 0; i < node.children.length; i++) {
getNode(node.children[i])
}
}
}
}
getNode(data[0])
How do I remove the object in my array subBrands that is nested inside another array where the id property of an object is = to 31. I'm trying to get the whole parent array back without that subBrand removed.
Array is:
[
{
"id": 10,
"name": "Parent Brand 1",
"parent": null,
"author": 1,
"deleted_at": null,
"created_at": "2017-02-02 09:55:51",
"updated_at": "2017-02-02 09:55:51",
"subBrands": [
{
"id": 31,
"name": "Sub Brand 6",
"parent": 10,
"author": 1,
"deleted_at": null,
"created_at": "2017-02-02 11:24:49",
"updated_at": "2017-02-02 11:42:02"
},
{
"id": 32,
"name": "Sub Brand 7",
"parent": 10,
"author": 1,
"deleted_at": null,
"created_at": "2017-02-02 11:24:57",
"updated_at": "2017-02-02 11:42:18"
},
{
"id": 33,
"name": "Sub Brand 8",
"parent": 10,
"author": 1,
"deleted_at": null,
"created_at": "2017-02-02 11:25:04",
"updated_at": "2017-02-02 11:42:34"
},
{
"id": 34,
"name": "Sub Brand 9",
"parent": 10,
"author": 1,
"deleted_at": null,
"created_at": "2017-02-02 11:25:39",
"updated_at": "2017-02-02 11:42:43"
},
{
"id": 35,
"name": "Sub Brand 10",
"parent": 10,
"author": 1,
"deleted_at": null,
"created_at": "2017-02-02 11:25:46",
"updated_at": "2017-02-02 11:42:52"
},
{
"id": 36,
"name": "Sub Brand 4",
"parent": 10,
"author": 1,
"deleted_at": null,
"created_at": "2017-02-02 11:43:53",
"updated_at": "2017-02-02 11:43:53"
}
]
},
{
"id": 12,
"name": "Parent Brand 2",
"parent": null,
"author": 1,
"deleted_at": null,
"created_at": "2017-02-02 09:56:16",
"updated_at": "2017-02-02 09:56:16",
"subBrands": []
},
{
"id": 16,
"name": "Brand no children",
"parent": null,
"author": 1,
"deleted_at": null,
"created_at": "2017-02-02 10:37:40",
"updated_at": "2017-02-02 10:37:40",
"subBrands": []
},
{
"id": 37,
"name": "Whoops brand",
"parent": null,
"author": 1,
"deleted_at": null,
"created_at": "2017-02-02 11:44:10",
"updated_at": "2017-02-02 11:44:10",
"subBrands": []
}
]
What I'm trying to get is:
[
{
"id": 10,
"name": "Parent Brand 1",
"parent": null,
"author": 1,
"deleted_at": null,
"created_at": "2017-02-02 09:55:51",
"updated_at": "2017-02-02 09:55:51",
"subBrands": [
{
"id": 32,
"name": "Sub Brand 7",
"parent": 10,
"author": 1,
"deleted_at": null,
"created_at": "2017-02-02 11:24:57",
"updated_at": "2017-02-02 11:42:18"
},
{
"id": 33,
"name": "Sub Brand 8",
"parent": 10,
"author": 1,
"deleted_at": null,
"created_at": "2017-02-02 11:25:04",
"updated_at": "2017-02-02 11:42:34"
},
{
"id": 34,
"name": "Sub Brand 9",
"parent": 10,
"author": 1,
"deleted_at": null,
"created_at": "2017-02-02 11:25:39",
"updated_at": "2017-02-02 11:42:43"
},
{
"id": 35,
"name": "Sub Brand 10",
"parent": 10,
"author": 1,
"deleted_at": null,
"created_at": "2017-02-02 11:25:46",
"updated_at": "2017-02-02 11:42:52"
},
{
"id": 36,
"name": "Sub Brand 4",
"parent": 10,
"author": 1,
"deleted_at": null,
"created_at": "2017-02-02 11:43:53",
"updated_at": "2017-02-02 11:43:53"
}
]
},
{
"id": 12,
"name": "Parent Brand 2",
"parent": null,
"author": 1,
"deleted_at": null,
"created_at": "2017-02-02 09:56:16",
"updated_at": "2017-02-02 09:56:16",
"subBrands": []
},
{
"id": 16,
"name": "Brand no children",
"parent": null,
"author": 1,
"deleted_at": null,
"created_at": "2017-02-02 10:37:40",
"updated_at": "2017-02-02 10:37:40",
"subBrands": []
},
{
"id": 37,
"name": "Whoops brand",
"parent": null,
"author": 1,
"deleted_at": null,
"created_at": "2017-02-02 11:44:10",
"updated_at": "2017-02-02 11:44:10",
"subBrands": []
}
]
I'm open to using underscores. The closest I'm come is:
var brands = _.filter(brands, function(n) {
return _.some(n.subBrands, function(subBrand){
return subBrand.id != brand.id;
});
});
But that removes the arrays that don't contain a subBrand with an id of 31. So it's not very close to what I need.
Cheers!
var arr = [{"id":10,"name":"Parent Brand 1","parent":null,"author":1,"deleted_at":null,"created_at":"2017-02-02 09:55:51","updated_at":"2017-02-02 09:55:51","subBrands":[{"id":31,"name":"Sub Brand 6","parent":10,"author":1,"deleted_at":null,"created_at":"2017-02-02 11:24:49","updated_at":"2017-02-02 11:42:02"},{"id":32,"name":"Sub Brand 7","parent":10,"author":1,"deleted_at":null,"created_at":"2017-02-02 11:24:57","updated_at":"2017-02-02 11:42:18"},{"id":33,"name":"Sub Brand 8","parent":10,"author":1,"deleted_at":null,"created_at":"2017-02-02 11:25:04","updated_at":"2017-02-02 11:42:34"},{"id":34,"name":"Sub Brand 9","parent":10,"author":1,"deleted_at":null,"created_at":"2017-02-02 11:25:39","updated_at":"2017-02-02 11:42:43"},{"id":35,"name":"Sub Brand 10","parent":10,"author":1,"deleted_at":null,"created_at":"2017-02-02 11:25:46","updated_at":"2017-02-02 11:42:52"},{"id":36,"name":"Sub Brand 4","parent":10,"author":1,"deleted_at":null,"created_at":"2017-02-02 11:43:53","updated_at":"2017-02-02 11:43:53"}]},{"id":12,"name":"Parent Brand 2","parent":null,"author":1,"deleted_at":null,"created_at":"2017-02-02 09:56:16","updated_at":"2017-02-02 09:56:16","subBrands":[]},{"id":16,"name":"Brand no children","parent":null,"author":1,"deleted_at":null,"created_at":"2017-02-02 10:37:40","updated_at":"2017-02-02 10:37:40","subBrands":[]},{"id":37,"name":"Whoops brand","parent":null,"author":1,"deleted_at":null,"created_at":"2017-02-02 11:44:10","updated_at":"2017-02-02 11:44:10","subBrands":[]}];
var id = prompt("Id of subbrands to remove: ");
arr.forEach(function(o) {
o.subBrands = o.subBrands.filter(s => s.id != id);
});
console.log(arr);
You could iterate the parent part, and the children and if found splice the object.
var data = [{ id: 10, name: "Parent Brand 1", parent: null, author: 1, deleted_at: null, created_at: "2017-02-02 09:55:51", updated_at: "2017-02-02 09:55:51", subBrands: [{ id: 31, name: "Sub Brand 6", parent: 10, author: 1, deleted_at: null, created_at: "2017-02-02 11:24:49", updated_at: "2017-02-02 11:42:02" }, { id: 32, name: "Sub Brand 7", parent: 10, author: 1, deleted_at: null, created_at: "2017-02-02 11:24:57", updated_at: "2017-02-02 11:42:18" }, { id: 33, name: "Sub Brand 8", parent: 10, author: 1, deleted_at: null, created_at: "2017-02-02 11:25:04", updated_at: "2017-02-02 11:42:34" }, { id: 34, name: "Sub Brand 9", parent: 10, author: 1, deleted_at: null, created_at: "2017-02-02 11:25:39", updated_at: "2017-02-02 11:42:43" }, { id: 35, name: "Sub Brand 10", parent: 10, author: 1, deleted_at: null, created_at: "2017-02-02 11:25:46", updated_at: "2017-02-02 11:42:52" }, { id: 36, name: "Sub Brand 4", parent: 10, author: 1, deleted_at: null, created_at: "2017-02-02 11:43:53", updated_at: "2017-02-02 11:43:53" }] }, { id: 12, name: "Parent Brand 2", parent: null, author: 1, deleted_at: null, created_at: "2017-02-02 09:56:16", updated_at: "2017-02-02 09:56:16", subBrands: [] }, { id: 16, name: "Brand no children", parent: null, author: 1, deleted_at: null, created_at: "2017-02-02 10:37:40", updated_at: "2017-02-02 10:37:40", subBrands: [] }, { id: 37, name: "Whoops brand", parent: null, author: 1, deleted_at: null, created_at: "2017-02-02 11:44:10", updated_at: "2017-02-02 11:44:10", subBrands: [] }];
data.some(function (a) {
return a.subBrands.some(function (b, i, bb) {
if (b.id === 31) {
bb.splice(i, 1);
return true;
}
});
});
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
I nest two forEach loops and return when the item has been found and removed:
let items = [{id: 1, subItems: [{id: 1}, {id: 2}]}];
const subItemToBeRemovedId = 1;
items.forEach((item) => item.subItems.forEach((subItem, index) => {
if (subItem.id === subItemToBeRemovedId) {
return item.subItems.splice(index, 1);
}
}));
console.log(items);
foreach seems to work:
var brands=[{id:10,name:"Parent Brand 1",parent:null,author:1,deleted_at:null,created_at:"2017-02-02 09:55:51",updated_at:"2017-02-02 09:55:51",subBrands:[{id:31,name:"Sub Brand 6",parent:10,author:1,deleted_at:null,created_at:"2017-02-02 11:24:49",updated_at:"2017-02-02 11:42:02"},{id:32,name:"Sub Brand 7",parent:10,author:1,deleted_at:null,created_at:"2017-02-02 11:24:57",updated_at:"2017-02-02 11:42:18"},{id:33,name:"Sub Brand 8",parent:10,author:1,deleted_at:null,created_at:"2017-02-02 11:25:04",updated_at:"2017-02-02 11:42:34"},{id:34,name:"Sub Brand 9",parent:10,author:1,deleted_at:null,created_at:"2017-02-02 11:25:39",updated_at:"2017-02-02 11:42:43"},{id:35,name:"Sub Brand 10",parent:10,author:1,deleted_at:null,created_at:"2017-02-02 11:25:46",updated_at:"2017-02-02 11:42:52"},{id:36,name:"Sub Brand 4",parent:10,author:1,deleted_at:null,created_at:"2017-02-02 11:43:53",updated_at:"2017-02-02 11:43:53"}]},{id:12,name:"Parent Brand 2",parent:null,author:1,deleted_at:null,created_at:"2017-02-02 09:56:16",updated_at:"2017-02-02 09:56:16",subBrands:[]},{id:16,name:"Brand no children",parent:null,author:1,deleted_at:null,created_at:"2017-02-02 10:37:40",updated_at:"2017-02-02 10:37:40",subBrands:[]},{id:37,name:"Whoops brand",parent:null,author:1,deleted_at:null,created_at:"2017-02-02 11:44:10",updated_at:"2017-02-02 11:44:10",subBrands:[]}];
brands.forEach(function(brand) {
brand.subBrands = brand.subBrands.filter(function(subBrand){
return subBrand.id != 31;
})
});
console.log(brands);
If you just need to look into the "subBrands" property of each item of your array, and you are using underscore, this works:
var myBrand = _.each(brands, function(brand) {
brand.subBrands = _.filter(brand.subBrands, function(subBrand) {
return subBrand.id != 31;
});
});
The jQuery way
function removeById(data, id){
$(data).each(function(i, e){
if(e.subBrands.length > 0){
$(e.subBrands).each(function(_i, _e){
if(_e.id == id){
e.subBrands.splice(_i,1);
return false;
}
});
}
});
return data;
}
console.log(removeById(data,32))
this function will return your whole data array without the specifiec id object
You can use for..of loop to iterate each subBrands array, Array.prototype.splice() to remove object having id 31 from array.
for (let {subBrands} of data) {
let n = 0;
for (let {id} of subBrands) {
if (id === 31) {
subBrands.splice(n, 1);
break;
}
++n;
}
}