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.
Related
I need to implement a button that cycles through these states in this array so that when the button is clicked State_1 in each object becomes State_2, then State_2 becomes State_3 and then goes back to State_1. The tricky part for me so far has been figuring out how to cycle only through the states in each object. Any suggestions would be greatly appreciated!
"people": [
{
"name": "Alice",
"State_1": "Apple",
"State_2": "Cherry",
"State_3": "Dates"
},
{
"name": "Bob",
"State_1": "Banana",
"State_2": "Plumb",
"State_3": "Clementine"
},
{
"name": "Eve",
"State_1": "Grapes",
"State_2": "Apricots",
"State_3": "Grapefruit"
}
]
}
So you want something like this? Let me know if I understood your question correctly.
const people = [
{
"name": "Alice",
"State_1": "Apple",
"State_2": "Cherry",
"State_3": "Dates"
},
{
"name": "Bob",
"State_1": "Banana",
"State_2": "Plumb",
"State_3": "Clementine"
},
{
"name": "Eve",
"State_1": "Grapes",
"State_2": "Apricots",
"State_3": "Grapefruit"
}
]
var saveState1
people.forEach(p => {
saveState1 = p.State_1
p.State_1 = p.State_2
p.State_2 = p.State_3
p.State_3 = saveState1
});
console.log(people)
I am getting an object from the backend with the following structure:
"periods": [
{
"id": 12,
"schemes": [
{
"id": 123,
"parts": [
{
"id": 1234,
"facts": {
"id": 21,
"basis": {
"id": 12344,
"amount": 10
},
"factor": {
"id": 1234,
"prop": 12
}
},
"deduction": {
"id": 133
},
"date": "22-10-2022",
"years": 12
},
{... more parts}
]
},
{... more schemes}
]
},
{... more periods}
]
I am changing the data and sending it back via a PATCH. The payload expects the id, the period.id, and an object with the same structure as above but only with the changed fields.
One example is, that I am changing the field amount. Then I need to know which part, which scheme and which period I am changing the amount in. And the object I am sending back should look something like this (the date should always be included):
{
"id": 22,
"schemes": [
{
"id": 43,
"parts": [
{
"id": 32,
"facts": {
"id": 77,
"basis": {
"id": 232,
"amount": 134 // CHANGING THIS
}
},
"date": "22-10-2022",
},
{... more parts}
]
},
{... more schemes}
]
}
At the moment I am solving it by taking the whole object from the backend and filtering out the one with the id and date (using the lodash filter function) which matches the one that changed, then creating a new object with those and the changed fields. Here is a snippet from my function:
if (name === "basis") {
const [period]: Period[] = _.filter(periods, {
schemes: [
{
parts: [
{
facts: {
id: data?.facts?.id,
basis: {
id: data?.facts?.basis?.id,
},
},
date: data?.date,
},
],
},
],
});
request = {
id: period?.id,
schemes: [
{
id: 2,
parts: [
{
id: data?.id,
facts: {
id: data?.facts?.id,
basis: {
id: data?.facts?.basis?.id,
amount: data?.facts?.basis?.amount,
},
},
date: data?.date,
},
],
},
],
};
}
return request;
I have an array of the keys of the changed fields in the state. And also a part-object with all the data and not only the changed data. My question is how I can create an object with the structure as above but only with changed data dynamically and not manually like I am doing right now?
Hey guys i have the following array:
Array [
Object {
"data": "Cat Man",
"id": "1",
},
Object {
"data": "Bat Girl",
"id": "2",
},
Object {
"data": "Mr Penguin",
"id": "3",
},
Object {
"data": "Cheeky Cheetah",
"id": "4",
},
]
I am going to take the users input in the form of a search bar, how can i sort the array based off the users input.
So lets say the user inputs
Bat g
the array would be sorted to:
Array [
Object {
"data": "Bat Girl",
"id": "2",
},
Object {
"data": "Cat Man",
"id": "1",
},
Object {
"data": "Mr Penguin",
"id": "3",
},
Object {
"data": "Cheeky Cheetah",
"id": "4",
},
]
How can I achieve this?
I have been searching around the array sort function:
Array.prototype.sort()
However I have only seen how to sort based off number comparisons I have never seen an array sorted based off string values like a search. Please could someone help me with this!
Here is function to search data using string text.
const searchItem = txt => {
let text = txt.toLowerCase();
let tracks = dataArray;
let filterTracks = tracks.filter(item => {
if (item.data.toLowerCase().match(text)) {
return item;
}
});
console.log('filterTracks', filterTracks);
};
Array Should be like this
var dataArray = [
{
data: 'Cat Man',
id: '1',
},
{
data: 'Bat Girl',
id: '2',
},
{
data: 'Mr Penguin',
id: '3',
},
{
data: 'Cheeky Cheetah',
id: '4',
},
];
I know how to operate on array of objects but never had the necessity to push one array data into another. I need to push an array of objects into another array with only 2 fields of the object. Right now my object format is somewhat like this
data: [{
"name": "Btech",
"courseid": "1",
"courserating": 5,
"points": "100",
"type": "computers"
},
{
"name": "BCom",
"courseid": "2",
"courserating": 5,
"points": "100",
"type": "computers"
}];
I want to push this into another array but I want only courseid and name in the object. I've read that we need to initialise the object in the constructor, use slice() and a few other functions and then push but I don't know how can I do it for mine since I need to push one array data into another.Kindly someone help me in this regard.
You're looking for the array map() method:
const newArray = array.map(o => {
return { name: o.name, courseid: o.courseid };
});
Try this:
let data = [{
"name": "Btech",
"courseid": "1",
"courserating": 5,
"points": "100",
"type": "computers"
},
{
"name": "BCom",
"courseid": "2",
"courserating": 5,
"points": "100",
"type": "computers"
}];
let other = []; // your other array...
data.map(item => {
return {
courseid: item.courseid,
name: item.name
}
}).forEach(item => other.push(item));
console.log(JSON.stringify(other))
// => [{"courseid":"1","name":"Btech"},{"courseid":"2","name":"BCom"}]
You can simply do it like this.
//assign your array of object to variable
var youArray:Array<any>= [{
"name": "Btech",
"courseid": "1",
"courserating": 5,
"points": "100",
"type": "computers"
},
{
"name": "BCom",
"courseid": "2",
"courserating": 5,
"points": "100",
"type": "computers"
}];
var resultArray:Array<any>=[] //empty array which we are going to push our selected items, always define types
youArray.forEach(i=>{
resultArray.push(
{
"name":i.name,
"courseid":i.courseid
});
});
console.log(resultArray)
if you still have doubts about this.please follow this url
Map to a returning JSON data, subscribe it to an existing array or an empty one. #typescript
let pictimeline= [];
var timeline = this.picService.fetchtimeline(this.limit)
.map((data : Response) => data.json())
.subscribe(pictimeline=> this.pictimeline = pictimeline);
console.log(this.pictimeline);
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