needs to added json parent array name to every sub array - arrays

Flutter / Dart Question
This is the array which I have , In the Accessories list it contains brand name("samsung"), I need to added the brand name to all the sub array.
you can see the second code space in the sub array of Brand name key it contains brand name of the parent key
{
"Accessories": [
{"id": 1,
"brand": "samsung",
"parentId": null,
"children": [
{
"id": 4,
"name": "Ace",
"parentId": 1
},
{
"id": 5,
"name": "note",
"parentId": 1
},
{
"id": 6,
"name": "galaxy",
"parentId": 1
}
]
},
{"id": 2,
"name": "Asus",
"parentId": null,
"children": [
{
"id": 7,
"name": "gaming",
"parentId": 2
},
{
"id": 8,
"name": "office",
"parentId": 2
}
]
},
]
}
what I expecting result is below
{
"phones": [
{
"id": 1,
"brand": "samsung",
"parentId": null,
"children": [
{
"id": 4,
"name": "Ace",
*"brand": "samsung",*
"parentId": 1
},
{
"id": 5,
"name": "note",
*"brand": "samsung",*
"parentId": 1
},
{
"id": 6,
"name": "galaxy",
*"brand": "samsung",*
"parentId": 1
}
]
},
{
"id": 2,
"name": "Asus",
"parentId": null,
"children": [
{
"id": 7,
"name": "gaming",
*"name": "Asus",*
"parentId": 2
},
{
"id": 8,
"name": "office",
*"name": "Asus",*
"parentId": 2
}
]
},
]
}
please help me to resolve the question .
..............................................................................................................................

Assuming you are not using any class to encode and decode json and you just want to get from the first json string to the second json string:
Map<String, dynamic> decodedMap = json.decode(accessoriesJson);
final List accessories = decodedMap['Accessories'];
final List result = accessories.map((a) {
return {
...a,
'children': (a['children'] as List)
.map((c) => ({...c, 'parent': a['brand']}))
.toList(),
};
}).toList();
final resultJson = json.encode({
'phones': result,
});
Note: I assumed the name of the parent on the first json is called brand (Like in the samsung example). Although in the Asus example it's called name.

You can create json decoder/encoder class with https://app.quicktype.io/
I used the same to convert the json to Accessories type.
After that you can use the forEach two times to update the existing array without creating a new one.
Like this
var list = Accessories.fromMap(json);
print(list.accessories);
list.accessories!.forEach((e) {
var brand = e.brand;
if (brand != null) {
e.children?.forEach((element) {
element.brand = brand;
});
}
});
print(list.toMap());
I am only using "brand" because
You should keep your property name same if using array.
Using "name" in parent will add property "name" in child. Which is wrong because there is already a property named "name" in child. So it will replace the child name.
Working example
https://dartpad.dev/?id=a7f4a869d02db3b929e3814db28fcbe1&null_safety=true
I had to make changes for null handling in type class as I don't know what will be the optional in this array. So I made everything optional.

Related

how to get values of the some keys in Array of Dictionary in Dart Flutter?

I have an Array of the Dictionary which the Dictionary contains many key values , I just want one keys values be in an array I do not want to loop Throw that with for loop I want some mapping but I do not know why it will sho0w me Error
So here is an Example
static final myDictionary = [
{
"id": 1,
"name": "Alex",
"field_of_work": "HR",
"description": ""
},
{
"id": 2,
"name": "Jack",
"field_of_work": "CEO",
"description": ""
},
{
"id": 3,
"name": "Eric",
"field_of_work": "Worker",
"description": ""
},
{
"id": 4,
"name": "Sam",
"field_of_work": "Computer",
"description": ""
},
{"id": 5, "name": "Michael", "field_of_work": "Others", "description": ""}
];
and I want my list be some thing like this
['Alex','Jack','Eric','Sam','Michael']
so here is the Code Which I wrote but Does not work (actually doe not compile)
myDictionary.asMap().values['name'].toList()
and here is the Error
The operator '[]' isn't defined for the type 'Iterable<Map<String, Object>>'.
Try defining the operator '[]'
try it like this
final List<String> namesList = myDictionary.map((e) => e["name"].toString()).toList();

Avoid using arrays (and [0]) in multidimensional JSON object

I'm storing data in a JSON file and need different objects/arrays. So far I am using the following structure:
data= [
{
"savedRuns": [
{
"id": 1,
"name": "Run 1"
},
{
"id": 2,
"name": "Run 2"
},
{
"id": 3,
"name": "Run 3"
}
]
},
{
"groups": [
{
"id": 1,
"name": "g1"
},
{
"id": 2,
"name": "g2"
},
{
"id": 3,
"name": "g3"
}
]
},
{
"locations": [
{
"id": 1,
"name": "home"
},
{
"id": 2,
"name": "work"
},
{
"id": 3,
"name": "school"
}
]
}
]
I would like to access the data in the file in an easy way, for instance:
console.log(data.savedRuns)
console.log(data.locations)
Unfortunately this returns undefined and the only way to access the data is:
console.log(data[0].savedRuns);
console.log(data[2].locations);
Since I don't necessarily know the position of the object, I would like to avoid that. If there a way around this, or a different structure to adopt for my file?
Link to JSFiddle
You have each attribute in a separate object, stored in an array. Get rid of the outer array and store the attributes in one object, then use data.savedRuns.
Thanks to Marks answer I could get the right syntax. Posting below in case of interest to others.
data = {
"savedRuns": [{
"id": 1,
"name": "Run 1"
},
{
"id": 2,
"name": "Run 2"
},
{
"id": 3,
"name": "Run 3"
}
],
"groups": [{
"id": 1,
"name": "g1"
},
{
"id": 2,
"name": "g2"
},
{
"id": 3,
"name": "g3"
}
],
"locations": [{
"id": 1,
"name": "home"
},
{
"id": 2,
"name": "work"
},
{
"id": 3,
"name": "school"
}
]
}

AngularJS prepare data for MultiBar Chart NVD3

I am calling my API to get JSON array below,
array = [{"date":1533791167870,"count":1,"name":"James"},{"date":1533791167870,"count":3,"name":"Kane"},{"date":1533791167918,"count":1,"name":"Kane"},{"date":1536203856526,"count":2,"name":"Trent"},{"date":1536217871371,"count":5,"name":"Kane"},{"date":1536217882525,"count":4,"name":"James"}]
And my name array,
name_array = ["Kane","Trent","James","Sam"]
I am using Lodash library. I would like to get my output array such that for each date all names are mapped from name_array and if there is count then get count value from array otherwise 0. I am expecting my output array as below result_array,
result_array = [{
"date": 1533791167870,
"count": 1,
"name": "James"
}, {
"date": 1533791167870,
"count": 3,
"name": "Kane"
},
{
"date": 1533791167870,
"count": 0,
"name": "Trent"
},
{
"date": 1533791167870,
"count": 0,
"name": "Sam"
}, {
"date": 1533791167918,
"count": 0,
"name": "James"
},
{
"date": 1533791167918,
"count": 1,
"name": "Kane"
},
{
"date": 1533791167918,
"count": 0,
"name": "Sam"
},
{
"date": 1533791167918,
"count": 0,
"name": "Trent"
}, {
"date": 1536203856526,
"count": 0,
"name": "James"
},
{
"date": 1536203856526,
"count": 0,
"name": "Kane"
},
{
"date": 1536203856526,
"count": 2,
"name": "Trent"
},
{
"date": 1536203856526,
"count": 0,
"name": "Sam"
}, {
"date": 1536217871371,
"count": 0,
"name": "James"
},
{
"date": 1536217871371,
"count": 5,
"name": "Kane"
},
{
"date": 1536217871371,
"count": 5,
"name": "Trent"
},
{
"date": 1536217871371,
"count": 5,
"name": "Sam"
}, {
"date": 1536217882525,
"count": 4,
"name": "James"
},
{
"date": 1536217882525,
"count": 0,
"name": "Trent"
}, {
"date": 1536217882525,
"count": 0,
"name": "Sam"
},
{
"date": 1536217882525,
"count": 0,
"name": "Kane"
}
]
I am doing this way for NVD3 AngularJS MultiBar chart. Since my array data is not working for the stacked view but group view is working fine.
I am using AngularJS, Lodash.
I would appreciate the help.
You can do it with several _.map calls:
let result = _.flatten(_.map(_.groupBy(array, 'date'), (existedEntries, date) => {
let usedNames = _.map(existedEntries, entry => entry.name);
let namesDiff = _.difference(name_array, usedNames);
let dateNumeric = parseFloat(date);
let enrichedNames = _.map(namesDiff, name => {
return {
date: dateNumeric,
count: 0,
name: name
};
});
return _.union(existedEntries, enrichedNames);
}));
First of all, we group existed entries by date, and for each group determine what names are used there. Then we calculate difference between all possible names and names used in the group. For each name from the difference we map it into default object with count: 0 and date equals to the date of current existing group. Next, we union existing values of the group with ones we got after enriching names diff. Final flatten call removes away temporal internal array structure.
In case if you use ES5 or lower, replace arrows syntax sugar with functions and let with var, i.e. var usedNames = _.map(existedEntries, function(entry) {return entry.name;});
P.S. In ES6 you can replace Lodash map function with eponymous native function, i.e. let usedNames = existedEntries.map(entry => entry.name);

Typescript : Find common objects from two array using Lambda function

I am using Typescript for below problem. I want to search object not simple alphabetic or number in the list.
Below are the two arrays.
I want to get common objects in separate list without using any third party library.
firstArray = [
{
"id": 4,
"name": "Tata"
},
{
"id": 11,
"name": "Maruti"
},
{
"id": 14,
"name": "Mahindra"
}
]
secondArray = [
{
"id": 4,
"name": "Tata"
},
{
"id": 11,
"name": "Maruti"
},
{
"id": 15,
"name": "Hyundai"
},
{
"id": 21,
"name": "Honda"
}
]
// Get Common Elements
// I am getting blank array as output
console.log(firstArray.filter(( make ) => secondArray.includes( make)));
Is there good function or way to find out commons element?
You can use array#filter with array#some. For each object in the first array, check if id and name exist in the other array.
const firstArray = [{ "id": 4, "name": "Tata" }, { "id": 11, "name": "Maruti" }, { "id": 14, "name": "Mahindra" } ],
secondArray = [{ "id": 4, "name": "Tata" }, { "id": 11, "name": "Maruti" }, { "id": 15, "name": "Hyundai" }, { "id": 21, "name": "Honda" } ],
result = firstArray.filter(o => secondArray.some(({id,name}) => o.id === id && o.name === name));
console.log(result);
For ES6, you can also try sets,
For demonstration,
const thirdArray = [...new Set([...firstArray ,...secondArray])];

How to Name an Array with an input

I have a Grocery List that I am able to create from an array of foods. What I am trying to do is name the array when I store it. I have my copy hung here Plunker
Currently the output looks like
[
{
"id": 3,
"name": "Coconuts"
},
{
"id": 2,
"name": "Peaches"
},
{
"id": 1,
"name": "Oranges"
}
]
I would like it to be something like
[
{"John's List":
{
"id": 3,
"name": "Coconuts"
},
{
"id": 2,
"name": "Peaches"
},
{
"id": 1,
"name": "Oranges"
}}
]
any thoughts or suggestions would be greatly appreciated.
updated your save function like below
$scope.save = function () {
var entity = {};
entity[$scope.name] = $scope.NewList;
$scope.MyList = angular.copy(entity);
};
from
$scope.save = function () {
$scope.MyList = angular.copy($scope.NewList);
};
checkout this update plunker
the JSON output is
{
"john's list": [
{
"id": 3,
"name": "Coconuts",
"Amount": 10,
"Price": 10
},
{
"id": 2,
"name": "Peaches",
"Amount": 5,
"Price": 5
}
]
}
does this matches your expected output??

Resources