Array conversion using JS - arrays

i'm new to Javascript and have sample set of array
[
{
"masterId": 56,
"type": "Alcohol Use",
"question": "Briefly describe any alcohol use - e.g. how many drinks a week?",
"answer": "5 alcohol consumed in a week"
},
{
"masterId": 57,
"type": "Allergies",
"questio": "Please list any allergies to medications or food.",
"answer": "Skin"
},
{
"masterId": 56,
"type": "Alcohol Use",
"questionn": "Which brand?",
"answer": "indian Monk"
}
]
basically i need to filter and convert this array based on masterId
This is an output which im expecting
[
{
"key": "Alchohol Use",
"value": [
{
"question": "Briefly describe any alcohol use - e.g. how many drinks a week?",
"answer": "5 alcohol consumed in a week"
},
{
"question": "Which brand?",
"answer": "indian Monk"
}
]
},
{
"key": "Allergies",
"value": [
{
"question": "Please list any allergies to medications or food",
"answer": "Skin"
}
]
}
]
im new to Javascript and aware of filter() method, but i can't develop a logic for above mentioned format.

let listOfQuestions = [{
"questionaireMasterId": 56,
"questionaireType": "Alcohol Use",
"questionnaireName": "Briefly describe any alcohol use - e.g. how many drinks a week?",
"questionaireAnswer": "5 alcohol consumed in a week"
},
{
"questionaireMasterId": 57,
"questionaireType": "Allergies",
"questionnaireName": "Please list any allergies to medications or food.",
"questionaireAnswer": "Skin"
},
{
"questionaireMasterId": 56,
"questionaireType": "Alcohol Use",
"questionnaireName": "Which brand?",
"questionaireAnswer": "indian Monk"
}
];
let questionaireTypeArray = [];
for (let i = 0; i < listOfQuestions.length; i++) {
questionaireTypeArray.push(listOfQuestions[i]['questionaireType']);
}
questionaireTypeArray = [...new Set(questionaireTypeArray)];
let finalArray = [];
for (let i = 0; i < questionaireTypeArray.length; i++) {
finalArray.push({
key: questionaireTypeArray[i],
value: [],
});
}
for (let i = 0; i < listOfQuestions.length; i++) {
for (let j = 0; j < finalArray.length; j++) {
if (finalArray[j]["key"] == listOfQuestions[i]["questionaireType"]) {
finalArray[j]["value"].push({
"question": listOfQuestions[i]["questionnaireName"],
"answer": listOfQuestions[i]["questionaireAnswer"],
});
}
}
}
console.log("Welcome to Programiz!", finalArray);

Related

How to filter a nested array of dictionaries with multiple conditions from another array in Swift

sample json data is this:
{
"variations": [
{
"variation_id": 391,
"name": "Fruit Shake - Chocolate, S",
"price": 10,
"attribute": [
{
"attribute_key": "pa_flavor",
"name": "Flavor",
"option": "Chocolate"
},
{
"attribute_key": "pa_size",
"name": "Size",
"option": "S"
}
]
},
{
"variation_id": 385,
"name": "Fruit Shake - Banana, L",
"price": 18,
"attribute": [
{
"attribute_key": "pa_flavor",
"name": "Flavor",
"option": "Banana"
},
{
"attribute_key": "pa_size",
"name": "Size",
"option": "L"
}
]
},
{
"variation_id": 386,
"name": "Fruit Shake - Banana, M",
"price": 15,
"attribute": [
{
"attribute_key": "pa_flavor",
"name": "Flavor",
"option": "Banana"
},
{
"attribute_key": "pa_size",
"name": "Size",
"option": "M"
}
]
}
]
}
my problem is, getting the variation_id where 2 or more attributes matches the array of string.
for example, chosenProduct = ["Banana", "L"]
I tried filter and contains but theres no way to match the other item from chosenProduct.
If I added the next condition, it returns nil
You can try this:
let varID = product.variations?.filter { att in
var matchedAttributes = 0
for thisAttribute in att.attribute {
if chosenProduct.contains(where: {$0 == thisAttribute.option}) {
matchedAttributes += 1
}
}
if matchedAttributes >= 2 {
return true
}
return false
}
Let me know if there's any doubt.
You can try this :
var chosenProduct = ["Banana","L"]
var expectedIds : [Int] = [Int]()
datas.variations?.map{ val in
val.attribute.map({ val2 in
let filtered = val2.enumerated().filter({chosenProduct.contains($0.element.option!)})
if filtered.count == chosenProduct.count{
expectedIds.append(val.variation_id!)
}
})
}
print(expectedIds) // [385]
I put the id's in array because of if you want to change your chosenProcudt example "Banana" (count 1 ). This mapping must be return variation_id like [385,386]
You can a method to Variation to make things easier:
extension Variation {
func attributesMatching(options: [String]) -> [Attribute] {
attribute.filter { options.contains($0.option) }
}
}
Then, you can just write:
let filtered = product.variations.filter { $0.attributesMatching(options: chosenProductOptions).count >= 2 }
print(filtered.map { $0.variationID })

I can't use filter when I have objects inside an array and find last id, angular

I need your opinion in this situation:
I get from API with this function:
getRS(
idProject: string
): Observable<ResponseModel<RSModel>> {
return this.http.get<ResponseModel<RSModel>>(
ApiUrlsConfig.getRS(
idProject
)
);
}
this response:
{
"data": [
{
"id": "id1",
"state": 1,
"note": null
},
{
"id": "id1",
"state": 2,
"note": "Reason 1"
},
{
"id": "id2",
"state": 2,
"note": "Reason updated3",
}
],
"result": null
}
I need to use filter in this response because I should be get the last state for each id. For example, I want to display state 2 in item with id: id1. For this I want to use filter. The problem is because I can't use filter on it, I don't understand why.
I tried to write this code:
#Input() set jobId(jobId: string) {
this.optionsService
.getRS(
this.idProject
)
.pipe()
.subscribe((res) => {
let resId = res.filter((aaa)=>{
if(aaa.id === jobId){
res.slice(-1)[0].id
}
}
)
});
}
Not function.
Please can you share with me any idea?
Thank you
Try this logic:
Loop backwards throw it.
Loop backwards over index to the start.
Splice duplicates.
let response = {
"data": [
{
"id": "id1",
"state": 1,
"note": null
},
{
"id": "id1",
"state": 2,
"note": "Reason 1"
},
{
"id": "id2",
"state": 2,
"note": "Reason updated3"
}
],
"result": null
}
let data = response.data;
for (let i = data.length - 1; i >= 0; i--) {
for (let j = i - 1; j >= 0; j--) {
if (data[i].id === data[j].id) {
data.splice(j, 1);
j++;
}
}
};
console.log(data);
try this:
if(aaa.id == jobId){
return res.slice(-1)[0].id
}

Traversing through an array of objects

{
"Catalog": {
"shirts": [
{
"id": "93453951-8427394-234723908",
"name": "Demin Shirt",
"price": 100.0,
"category": "Random Category",
"available": true,
},
{
"id": "93453951-8427394-40325978",
"name": "Random Shirt",
"price": 500.0,
"category": "Random Category",
"available": true,
}
],
"Jeans": [
{
"id": "4802345-348579-5983452-23423",
"name": "Bare Denim Jeans",
"price": 2000.0,
"category": "Some Category",
"available": true,
},
{
"id": "143682137-3481293-239842",
"name": "Levis jeans",
"price": 1000.0,
"category": "Some Category",
"available": true,
}
]
}
}
How do I traverse this array of objects such that I am able to display all the different types of shirt under the category shirt and all the jeans under the heading jeans.
Something like this:
Shirts
Denim Shirt.
Random Shirt
Jeans
Bare Denim Jeans
Levis jeans
Generic Solution
This is an object, not a list, so you can't just plug it into a loop. If you want to loop through all the values and sub-values, you will have to do it recursively.
void recurseObject(dynamic value) {
if (value is List) {
// value is a list, iterate over its children
for (var child in value) {
recurseObject(object);
}
} else if (value is Map) {
// value is an object, iterate over its keys and recurse the corresponding values
for (var key in object.keys) {
print(key);
recurseObject(object[key]);
}
} else {
// value is a primitive, so just print it
print(value);
}
}
Specific to your Object
If your object has a set structure, then you can just grab all the bits you want and set up some nested loops.
final catalog = rootObj['Catalog'] as Map<String, Dynamic>;
for (var category in catalog.keys) {
final categoryList = catalog[category] as List<dynamic>;
print(category);
for (var value in categoryList) {
final name = value['name'];
print(name);
}
}
What you have there is pure JSON. You need to first convert it into a Dart object.
There are a few ways to do the conversion. I've found the easiest way is to use an online converter such as this website: https://app.quicktype.io/
After you convert your JSON to an object, you could traverse it like this:
printCatalog() {
var catalog =
Catalog.fromRawJson("Here's where you need to pass in your JSON");
print("Shirts: ");
catalog.shirts.forEach((shirt) {
print(shirt.name);
});
print("Jeans: ");
catalog.jeans.forEach((jean) {
print(jean.name);
});
}
Just use dart:convert library, and json.decode. Then access whatever you want in your json.
I fixed your JSON as it wasn't set up right, here is the complete solution.
import 'dart:convert';
void main() {
var jsonstring = '''{
"Catalog": {
"shirts": [{
"id": "93453951-8427394-234723908",
"name": "Demin Shirt",
"price": 100.0,
"category": "Random Category",
"available": "true"
},
{
"id": "93453951-8427394-40325978",
"name": "Random Shirt",
"price": 500.0,
"category": "Random Category",
"available": true
}
],
"Jeans": [{
"id": "4802345-348579-5983452-23423",
"name": "Bare Denim Jeans",
"price": 2000.0,
"category": "Some Category",
"available": true
},
{
"id": "143682137-3481293-239842",
"name": "Levis jeans",
"price": 1000.0,
"category": "Some Category",
"available": true
}
]
}
}''';
Map<String, dynamic> data = json.decode(jsonstring);
print("--COOL SHIRTS--");
for (var shirt in data["Catalog"]["shirts"]) {
print(shirt["name"]);
}
print("\n--COOL JEANS--");
for (var jeans in data["Catalog"]["Jeans"]) {
print(jeans["name"]);
}
}
Output:
--COOL SHIRTS--
Demin Shirt
Random Shirt
--COOL JEANS--
Bare Denim Jeans
Levis jeans

How to fetch data from a nested array in a JSON file?

I have fetched data from a JSON file.. But when I tried to fetch another data from it, am unable to do so as it is a nested array... I know the solution can arrive easily but this is the first time am trying to loop a JSON file.. so kindly give your inputs.
SampleData = {
"squadName": "Super hero squad",
"homeTown": "Metro City",
"formed": 2016,
"secretBase": "Super tower",
"active": true,
"members": [
{
"name": "Molecule Man",
"age": 29,
"secretIdentity": "Dan Jukes",
"powers": [
"Immortality",
"Turning tiny",
"Radiation blast"
]
},
{
"name": "Madame Uppercut",
"age": 39,
"secretIdentity": "Jane Wilson",
"powers": [
"Million tonne punch",
"Damage resistance",
"Superhuman reflexes"
]
},
{
"name": "Eternal Flame",
"age": 1000,
"secretIdentity": "Unknown",
"powers": [
"Immortality",
"Heat Immunity",
"Inferno",
"Teleportation",
"Interdimensional travel"
]
}
]
};
GetJsonData() {
console.log(this.SampleData["powers"]);
for (let i = 0; i < this.SampleData["powers"].length; i++) {
if (this.SampleData["powers"][i].Immortality) {
console.log(this.SampleData.powers[i]);
}
}
}
{name: "Molecule Man", age: 29, secretIdentity: "Dan Jukes", powers: Array(3)}
{name: "Eternal Flame", age: 1000, secretIdentity: "Unknown", powers: Array(3)}
Your code needs to follow the structure of the JSON data; in particular, these are all valid things you could print:
console.log(this.SampleData.squadName);
console.log(this.SampleData.homeTown);
console.log(this.SampleData.members[0].name);
console.log(this.SampleData.members[0].powers[0]);
If you wanted to loop through each member and print their info, that might look like this:
this.SampleData.members.forEach(member => {
let powerString = member.powers.join(', ');
console.log('Name: ' + member.name);
console.log('Age: ' + member.age);
console.log('Powers: ' + powerString);
});
I used a forEach, but you can also use a for (let i = loop.

How can I change the attribute in dataset of Fusionchart?

Hi I am implementing a chart in my Angularjs Application, You can see this plunker http://jsfiddle.net/fusioncharts/73xgmacm/ The thing which I want to achieve is to change the value attribute to profit. How can I do this ? I want to display profit not values.
Regards
After 2 days I finally find out the answer. The thing is You cannot change the Fusionchart attribute value but you can change the attribute of your API once you fetched. I used a loop after I fetched the API and replace the 'profit' attribute with value in this way I made the chart. Yes The thing which i had been ignoring was the use of 'variable' instead of scope. If you see this example you would understand Example Here. I am sharing my code May be it helps someone else too.
Give below is my json array which i called tps.json
[
{
"index": "1",
"variantoption": "fan-green",
"company": "sk fans",
"quantity": "650",
"profit": "78296",
"loss": "8457",
"year": "2016"
},
{
"index": "2",
"variantoption": "fan-white",
"company": "al ahmed fans",
"quantity": "450",
"profit": "78296",
"loss": "8457",
"year": "2016"
},
{
"index": "3",
"variantoption": "fan-purple",
"company": "asia fans",
"quantity": "350",
"profit": "78296",
"loss": "8457",
"year": "2016"
},
{
"index": "4",
"variantoption": "fan-yellow",
"company": "falcon fans",
"quantity": "250",
"profit": "78296",
"loss": "8457",
"year": "2016"
}
]
and here is my controller
$http.get('js/tps.json').success(function (data) {
var chartdata = data;
var arrLength = chartdata.length;
console.log(arrLength);
for (var i = 0; i < arrLength; i++) {
if (chartdata[i]['profit'] && chartdata[i]['index']) {
chartdata[i].value = chartdata[i].profit;
delete chartdata[i].profit;
chartdata[i].label = chartdata[i].index;
delete chartdata[i].index;
console.log(chartdata);
}
}
console.log(chartdata);
FusionCharts.ready(function () {
var tps = new FusionCharts({
type: 'column2d',
renderAt: 'chart-container',
width: '500',
height: '300',
dataFormat: 'json',
dataSource: {
"chart": {
"caption": "Monthly",
"xaxisname": "Month",
"yaxisname": "Revenue",
"numberprefix": "$",
"showvalues": "1",
"animation": "1"
},
"data" : chartdata
}
});
tps.render();
});
}
);
}
-Stay foolish stay hungry

Resources