Javascript array object creation with unique value as key - javascript

I have an array of objects, like this:
[{
"name": "xxx",
"order": 1,
"layerDtos": [{
"id": 1,
"dataType": 1
}, {
"id": 1,
"dataType": 2
}, {
"id": 1,
"dataType": 3
}]
},
{
"name": "yyy",
"order": 1,
"layerDtos": [{
"id": 1,
"dataType": 4
}, {
"id": 1,
"dataType": 5
}]
}
]
I want to create any object with key/value pairs as { 1: [ xxx, yyy ] }. I want to put all names in an array whose id inside layerDtos objects are the same.
Can someone explain how can I handle this? I tried using map() though it's not working and I am getting object like {1:xxx},{1:yyy} however, I need {1: [xxx,yyy]}

Related

Parse json object and read values

I want to be able to parse this json tree and get the value of the attribute checked for every element :
{
"children": [
{
"children": [
{
"children": [],
"id": 49,
"name": "nice",
"checked": true,
"level": 3,
"path": "0_1_0_0",
"lineLength": 180
}
],
"id": 48,
"name": "amira",
"checked": false,
"level": 2,
"path": "0_1_0"
}
],
"id": 47,
"name": "mahdi",
"checked": true,
"level": 1,
"path": "0_1"
}
I'm able to read the data this way :
var data = this.flatData;
I want to be able to read the checked attribute for every child inside a for loop or a foreach and if it's true set a certain behaviour to my code do any one know how to do this and thanks in advance.
You can use a recursion; in your particular structure something like:
const func = (elem) => {
if (elem.children) elem.children.forEach((elem) => func(elem));
if (elem.checked) console.log(`act on elem with id: ${elem.id}`);
}
func(test);

Remove item from items array

Remove item from items array and return new list array
list: [
{
"id": 1,
"name": "john",
"items": [
{
"id": 2,
"name": "michael",
},
{
"id": 3,
"name": "mohamed",
}
}]
Your question is not at all clear. You want to remove item from items array, but with respect to what you haven't mentioned. So I provided that condition myself. My code removes items based on the given id. If id is 2 the object inside the items array removes the object which has the id property set to 2.
var list=
[
{ "id": 1, "name": "john", "items":
[ { "id": 2, "name": "michael", },
{ "id": 3, "name": "mohamed", } ]}]
var id=2;
var r=list.forEach((w)=>{
w.items.forEach((u)=>{
if(u.id==id)
{w.items.splice(w.items.indexOf(u),1);}
})
})
console.log(list[0].items[0]);

Deserialize possible children, which might have properties that needs to be deserialized

On my ASP.NET backend, I return an array of models, called Job, that can have n amount of jobs as children, using SignalR. One job could look like this:
{
"id": 0,
"json": '{"error": "Some error"}',
"children": [{
"id": 1
}, {
"id": 3,
"children": [{
"id": 4,
"json": '{"error": "Some other error"}'
}]
}]
}
As you can see, each job can have a child, which can have another child, and so on. Each job also has a json property, which is JSON in a text string. I want to deserialize these to a regular JavaScript object, which looks like this:
var deserialized = {
"id": 0,
"json": {
"error": "Some error"
},
"children": [{
"id": 1
}, {
"id": 3,
"children": [{
"id": 4,
"json": {
"error": "Some other error"
}
}]
}]
}
So basically goes like this:
If the job has a json property simply do job.json = JSON.parse(job.json)
If the job has children, loop over all the children
Repeat 1
How can I achieve this? I guess recursion is a way, but I'd rather see if it's possible to utilize the new ES6 methods.
1.If the job has a json property simply do job.json = JSON.parse(job.json)
2.If the job has children, loop over all the children
3.Repeat 1
Suppose, in a job you have both properties json with JSON string and also children then we have to execute both the points (1 & 2) one by one to convert the nested json property of the job into JSON Object.
In that case, first we have to convert the json property into JSON Object and then again we have to iterate the whole job with children array.
Try Array filter() method with ES6 Arrow function.
Working Demo :
let jobs = [{
"id": 0,
"json": '{"error": "Some error"}',
"children": [{
"id": 1
}, {
"id": 3,
"children": [{
"id": 4,
"json": '{"error": "Some other error"}'
}]
}]
},
{
"id": 1,
"json": '{"error": "Some error"}',
"children": [{
"id": 2
}, {
"id": 4,
"children": [{
"id": 5,
"json": '{"error": "Some other error"}'
}]
}]
}];
function parseObj(job) {
let res;
if (typeof job !== 'object') {
return;
} else {
res = job.filter(elem => (elem.json && typeof elem.json == 'string')?elem.json = JSON.parse(elem.json):parseObj(elem.children))
.filter(elem => (elem.json && typeof elem.json == 'string')?elem.json = JSON.parse(elem.json):parseObj(elem.children));
}
return res;
}
console.log(parseObj(jobs));

filtering JSON object on an object inside an object

I have some data looking like:
var items = [
{ "id" : 1,
"title" : "this",
"groups" : [
{"id" : 1,
"name" : "groupA"},
{"id" : 2,
"name" : "groupB"}
]
},
{ "id" : 2,
"title" : "that",
"groups" : [
{"id" : 1,
"name" : "groupA"},
{"id" : 3,
"name" : "groupC"}
]
},
{ "id" : 3,
"title" : "other",
"groups" : [
{"id" : 3,
"name" : "groupC"},
{"id" : 2,
"name" : "groupB"}
]
}]
And I want to filter based on the group ids but I'm having trouble even accessing them - item.group returns the whole object and doing anything else (i.e. item.groups.id) returns a null or undefined value.
Any help about how to do this would be great. Essentially I want to filter the array to include all items that are in a specific group.
Thanks
Try this:
group3Items = items.filter(item => item.groups.findIndex(group => group.id==3) > -1)
You can do like this
var items = [{
"id": 1,
"title": "this",
"groups": [{
"id": 1,
"name": "groupA"
}, {
"id": 2,
"name": "groupB"
}]
}, {
"id": 2,
"title": "that",
"groups": [{
"id": 1,
"name": "groupA"
}, {
"id": 3,
"name": "groupC"
}]
}, {
"id": 3,
"title": "other",
"groups": [{
"id": 3,
"name": "groupC"
}, {
"id": 2,
"name": "groupB"
}]
}]
// A filter function to filter out the matched value
function filterArray(array, val) {
return array.filter(function(elem) {
return elem.id === val; // filtering by Id
})
}
// first filtering the original items array, & will get the object where id is 1
var obj = filterArray(items, 1);
//the previous result will return an array,
//so doing obj[0] which will give the first index.
//obj[0].groups will be an array again
var filterGroup = filterArray(obj[0].groups,1) // will be an array which contains the matched group
DEMO
Use:
Array.prototype.map to create a new array mapping every item in the array to a new object by
cloning every item using the spread operator* and override the groups key with a new array made from the original by using
Array.prototype.filter to keep only the objects with the correct id.
*need a transpiler such as babel or typescript though
OR
If you wanted to flatten the structure, then you could use Array.prototype.reduce to combine the arrays.
The code below has two outputs:
one keeps the original structure but filters out the items in the group that don't have an id of 3.
one flattens the structure and outputs just one array.
const items = [{
"id": 1,
"title": "this",
"groups": [{
"id": 1,
"name": "groupA"
},
{
"id": 2,
"name": "groupB"
}
]
},
{
"id": 2,
"title": "that",
"groups": [{
"id": 1,
"name": "groupA"
},
{
"id": 3,
"name": "groupC"
}
]
},
{
"id": 3,
"title": "other",
"groups": [{
"id": 3,
"name": "groupC"
},
{
"id": 2,
"name": "groupB"
}
]
}
];
const filteredRemovingGroups = items.map(item => ({
...item,
groups: item.groups.filter(subItem => subItem.id === 3)
}));
const filterAndFlatten = items.map(item =>
item.groups.filter(subItem => subItem.id === 3)
).reduce((combinedArr, arr) => [...combinedArr, ...arr], [])
console.log('filteredRemovingGroups', filteredRemovingGroups);
console.log('filterAndFlatten', filterAndFlatten);

Compare two arrays and update with the new values by keeping the existing objects using javascript-Not working for delete operation of objects

This is a follow up question for Compare two arrays and update with the new values by keeping the existing objects using javascript which was ansewered by #Siderite Zackwehdex
Please check this plunker I'm getting the deleted Object in the changedArray1.Is there any option to fix this.Its working fine for other changes like add,update but not for delete.
One feature that I tried to implement is to add an additional object ie., "removedIds":[23] , that holds the deleted id's as an array in each level of objects and identifying them in the evaluation process.. but didn't find the right soultion
Example data:
var parentArray1=[
{
"id": 1,
"name": "test",
"context": [
{
"operationalContextId": 1.1,
"valueChainEntityDetails": [
{
"valuChainEntityId": 3,
"name": "test",
"context": [
{
"id": 3.1,
"name": "test 3.1",
"activityDetails": [
{
"activityId": 22,
"name": "test 3.1"
},
{ //trying to remove activity id 23
"activityId": 23,
"name": "changed test 23"
}
]
}
]
}
]
}
]
}
]
var changedArray1=[
{
"id": 1,
"name": "test2",
"context": [
{
"operationalContextId": 1.1,
"valueChainEntityDetails": [
{
"valuChainEntityId": 3,
"name": "changed test3",
"context": [
{
"id": 3.1,
"name": "test 3.1",
"removedIds":[23] ,
"activityDetails": [ //activity id 23 is removed in this JSON but reflecting in parentArray1
{
"activityId": 22,
"name": "changed test 3.1"
}
]
}
]
}
]
}
]
}
]

Categories