angular js - try to overwrite an existing object parts with no success - javascript

i building a monthly report for a customer via google analytics api, i built a factory function to handle the requests and everything, i get this json array from inside the factory function:
var months = {
paid_traffic: [
{plan: "", sales: ""},{plan: "", sales: ""},{plan: "", sales: ""},
{plan: "", sales: ""},{plan: "", sales: ""},{plan: "", sales: ""},
{plan: "", sales: ""},{plan: "", sales: ""},{plan: "", sales: ""},
{plan: "", sales: ""},{plan: "", sales: ""},{plan: "", sales: ""}
],
each object inside the array represent a month plan and sales.
i get details from google analytics and fill the object with it, till here everything works just fine, later on i need to calculate the total traffic for each month (i have few more object looks like that represent different google segments).
i have a problem with getting the results i garbed before in from google, it's keep return the empty initialized object my code look like this:
function calcTotalTraffic(){
for(var i in months.paid_traffic){
console.log(i,months.paid_traffic[i],months.paid_traffic);
}
}
my console.log looks like this from some wired reason:
0 Object {plan: "", sales: ""} [Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]
the last result (for the console.log(months.paid_traffic)) look like that when opened :
0: Object$$hashKey: "object:13"plan: ""sales: 99601__proto__: Object1: Object$$hashKey: "object:14"plan: ""sales: 93185__proto__: Object2: Object3: Object4: Object5: Object6: Object7: Object8: Object9: Object10: Object11: Object
as you can see from some reason it's return the original empty object.
any idea why it is happening??
p.s even if i manually months.paid_traffic[0] it'r return the same empty row..
thanks for the help, i appreciate it :)

Related

Having Trouble Selecting array in Javascript

new to Javascript. Attempting to pull data from a weather API for a project but have run into an issue that I'm sure is simple to solve. Here is the data I've fetched already:
{coord: {…}, weather: Array(1), base: "stations", main: {…}, visibility: 9656, …}
coord: {lon: -76.13, lat: 43.04}
weather: Array(1)
0: {id: 500, main: "Rain", description: "light rain", icon: "10d"}
length: 1
__proto__: Array(0)
base: "stations"
main: {temp: 281.12, feels_like: 274.24, temp_min: 280.37, temp_max: 282.04, pressure: 1004, …}
visibility: 9656
wind: {speed: 8.2, deg: 310}
rain: {1h: 0.25}
clouds: {all: 90}
dt: 1587324361
sys: {type: 1, id: 5965, country: "US", sunrise: 1587291309, sunset: 1587340289}
timezone: -14400
id: 0
name: "Syracuse"
cod: 200
__proto__: Object
What I need to do is select "Rain" under the weather class. However, since it is inside of an array I do not know how to get it. For example, if I do
data.visibility
I will of course be returned with 9656. Yet if I do
data.weather.0 or even data.weather.["0"]
I will be met with the following error: Uncaught SyntaxError: Unexpected number. And even if I were to not get this error, how would I go about accessing the specific element "Rain" in the Array?
Sorry if this is an easy fix, just having trouble finding an answer due to the very specific wording whenever I search.
If you need only the first element of an array, you can simply use an index to get the value data.weather[0].main.
Or you can map an array via the Array method data.weather.map(item => item.main). You will get a customized array ["Rain"]
You access it like this:
data.weather[0].main
where 0 is an integer describing the index of the element of the array.

Changing a deeper property of an object shows in console but not when we open it or access it later

Changing a deeper property of an object shows in console but not when we open it or access it later.The below is my object :
section#shikhar:
1: {displayName: "Entity", dropdownType: "SINGLESELECT", fieldType: "DROPDOWN", values: Array(24), template: null, …}
2:
customTooltip: null
defaultValue: null
dependentValues: {AVS - Avionics: Array(4), DMS - Defence Mission Systems: Array(4), LAS - Land and Air Systems: Array(5), SIX - Secure Communications & Information Systems: Array(4), GTS - Ground Transportation Systems: Array(4), …}
displayName: "Business Line"
dropdownType: "SINGLESELECT"
fieldType: "DROPDOWN"
isDashboard: true
isOptional: false
isParentOf: "3"
isReporting: true
isTooltipEnabled: null
parent: 1
parentValue: ["depend"]
productTooltip: null
sequenceNumber: 2
template: null
values: []
__proto__: Object
3: {displayName: "Product Line Family", dropdownType: "SINGLESELECT", fieldType: "DROPDOWN", values: Array(0), template: null, …}
4: {displayName: "Product Line", dropdownType: "SINGLESELECT", fieldType: "DROPDOWN", values: Array(0), template: null, …}
5: {displayName: "Brief Instructions", dropdownType: null, fieldType: "TEXT", values: null, template: null, …}
6: {displayName: "Main message", dropdownType: null, fieldType: "TEXT", values: null, template: null, …}
7: {displayName: "Tone of voice", dropdownType: "MULTISELECT", fieldType: "DROPDOWN", values: Array(10), template: null, …}
8: {displayName: "Audience to address (Primary)", dropdownType: "MULTISELECT", fieldType: "DROPDOWN", values: Array(2), template: null, …}
9: {displayName: "Target to reach (Secondary)", dropdownType: "MULTISELECT", fieldType: "DROPDOWN", values: Array(9), template: null, …}
10: {displayName: "Sub-type", dropdownType: "SINGLESELECT", fieldType: "DROPDOWN", values: Array(2), template: null, …}
11: {displayName: "Size", dropdownType: "SINGLESELECT", fieldType: "DROPDOWN", values: Array(0), template: null, …}
12: {displayName: "Custom Size", dropdownType: null, fieldType: "TEXT", values: Array(0), template: null, …}
13: {displayName: "Copyrights: Expiry Date", dropdownType: null, fieldType: "DATE", values: null, template: null, …}
14: {displayName: "Output Format", dropdownType: "SINGLESELECT", fieldType: "DROPDOWN", values: Array(4), template: null, …}
15: {displayName: "Other", dropdownType: null, fieldType: "TEXT", values: Array(0), template: null, …}
16: {displayName: "Tags", dropdownType: null, fieldType: "TEXT", values: null, template: null, …}
Here the problem is that even though I am setting the values inside the "2" object it still shows it as [] but actually it should have 4 values like :
{displayName: "Business Line", dropdownType: "SINGLESELECT", fieldType: "DROPDOWN", values: Array(4), template: null, …
I know the object is getting mutated somehow because even the console says that the value was evaluated just now.
The code I am using being :
updateAllCommonValues=(val,id)=>{
const { commonTemplateFields } = this.state;
var commonTemplateValues = JSON.parse(JSON.stringify(commonTemplateFields));
_.forEach(commonTemplateValues,(section,k)=>{
_.forEach(section,(field,key)=>{
if(key == id){
field.value = val
if(field.isParentOf != null){
commonTemplateValues[k][Number(field.isParentOf)]['values'] = section[field.isParentOf].dependentValues[val];
}
}
})
})
this.setState({
commonTemplateFields:commonTemplateValues
},()=>{
this.props.updateFinalPojo('orderInfo',commonTemplateValues);
})
}
The correct value of commonTemplateFields is not coming to setstate i.e. the array for values instead it is empty as the initial state.
PS: It passes all if conditions.
PPS : Object structure :
{
"values":[
"Flight Avionics (FLX)",
"In-Flight Entertainment (IFE)",
"Training & Simulation (T&S)",
"Microwave & Imaging (MIS)"
],
"parent":1,
"parentValue":[
"depend"
],
"dependentValues":{
"AVS - Avionics":[
"Flight Avionics (FLX)",
"In-Flight Entertainment (IFE)",
"Training & Simulation (T&S)",
"Microwave & Imaging (MIS)"
],
"DMS - Defence Mission Systems":[
"Above Water Systems (AWS)",
"Electronic Combat Systems (ECS)",
"Intelligence Surveillance & Reconnaissance (ISR)",
"Under Water Systems (UWS)"
],
},
"isParentOf":"3"
}
There isn't enough in your question to know the structure of what you're updating precisely, but in general, JSON.parse(JSON.stringify(...)) is a lossy way to clone objects (also slow, as it makes a trip through JSON). There's also no need to clone the entire structure, just the parts you're changing.
Separately, any time you're setting state based on existing state, you must use the callback version of setState, because state updates are asynchronous so if you don't use the callback version, you could be using stale source state information.
If I'm reading your code correctly, commonTemplateFields is either an array or an object containing sections, which are either arrays or objects containing fields, which are objects. So here's how you would update the field(s) whose field key is id (see comments):
updateAllCommonValues = (val,id) => {
// Must use callback version of `setState`
this.setState(
({commonTemplateFields}) => {
// Get a shallow copy of `commonTemplateFields`
commonTemplateFields = {...commonTemplateFields}; // Or `= [...commonTemplateFields]` if it's an array
// Loop through the sections and their fields
_.forEach(commonTemplateFields, (section, sectionKey) => {
_.forEach(section, (field, fieldKey) => {
if (fieldKey == id) {
// Need to update this field, shallow copy the section
section = commonTemplateFields[sectionKey] = {...section}; // Or = `[...section]`, I can't tell whether section is an object or array
// Shallow copy and update the field
field = section[fieldKey] = {...field, value: val};
if (field.isParentOf != null) {
// Shallow copy and update the dependent field
const index = Number(field.isParentOf);
section[index] = {...section[index], values: section[index].dependentValues[val]};
}
}
});
});
// Return the update
return {commonTemplateFields};
},
() => {
this.props.updateFinalPojo('orderInfo', this.state.commonTemplateFields);
}
);
}
Hopefully, between the JSON thing and the async thing, that helps sort out the issue.
Side note: FWIW, in modern JavaScript there's no need for _.forEach, and using _.forEach can make the code less readable by hiding the structure of your data. If you're looping through an array, you can use the built-in forEach or a for-of loop as appropriate (the for-of might be on the array itself, or on the result of calling its entries method if you need both value and index). If you're looping through the contents of an object, you can use for-of loop on Object.keys, Object.values, or Object.entries depending on what you're doing.
Obviously, though, if you simply prefer _.forEach, that's a style choice you're entirely entitled to make. :-)
I figured out the solution to this and posting this as it might be helpful to someone else as well. When we do looping over nested object it appears as if the comparision is made only on the first level. The property I was changing was at 3rd level. Maybe I am wrong but this is the conclusion I have arrived on coz when I made another change at the first level, the value change at 3rd level started to show as well.

How Best to Handle Iterating Over Sub-Data in Angular App

In my Angular app with a MongoDB/Node backend, I have been successfully iterating over an array of records and printing them to the view in a table layout - one line per object in the array.
Now I have a situation where I need to break out what was information on one line into three lines, based on info in a "subdata" object. A simplified version of the data looks like this:
data: [
{
name: {
first: "John,
last: "Smith
},
referred: true,
birthDate: date,
city: "New York",
createDate: date,
subdata: {
a: "value a",
b: "value b",
c: "value c"
},
deleted: false
}
]
Rather than iterating once for each object in the "data" array, which I was doing before like this:
<tr *ngFor="let record of records.data | paginate: { id: 'results', itemsPerPage: 12, currentPage: getPageNumber(), totalItems: records.count }">
... I instead need to now print three lines - one for each of the values in the "subdata" object. But each of those lines needs to include the name, the birthDate, and the city that is part of the parent object.
From an architectural point of view, does it make it more sense to create a new backend endpoint, and populate the data in the format I want to iterate over it by (which would involve some repetition of props and values (name, birthDate, city, etc...), like this:
reOrgedData: [
{
name: {
first: "John,
last: "Smith
},
referred: true,
birthDate: date,
city: "New York",
createDate: date,
a: value
deleted: false
},
{
name: {
first: "John,
last: "Smith
},
referred: true,
birthDate: date,
city: "New York",
createDate: date,
b: value
deleted: false
},
{
name: {
first: "John,
last: "Smith
},
referred: true,
birthDate: date,
city: "New York",
createDate: date,
c: value
deleted: false
}
]
or is there a way I can iterate over this in its original data structure, but still break it out into three lines in the view?
My sense is that creating a custom endpoint with the data organized in the form I need is the way to go, even though that does involve some repetition. This approach makes for less hoops-jumping on the front-end. But I am curious for people's take on what would be the best approach in a scenario like this.

How to get array from json footable

I'm trying to get the data with json to generate a footable table with pagination but it's not working.
my code actualy look like this.
sorry my bad english.
my index.json is returning it
{
Cartas: [
{
id: 3,
user_id: 1,
status: "2",
banco_cartas: null,
nome: "teste",
contrato: "",
grupo: "430",
cota: "3332",
credito_atual: 154371.02,
prazo_original: "",
prazo_atual: "126",
valor_parcela: "0",
pc_pago: 1,
pc_fc: 0,
valor_pago: 154371.02,
saldo_devedor: null,
taxa: 0,
data_compra: "2003-03-28T00:00:00+00:00",
created: "2017-06-22T17:39:23-03:00",
data_contemplacao: "2016-12-20T00:00:00+00:00",
data_entrega: null
},
{
id: 4,
user_id: 1,
status: "2",
banco_cartas: null,
nome: "CAS REP comerciais",
contrato: "",
grupo: "240",
cota: "320",
my jquery to load the json in footable
jQuery(function($){
$('#custom-ui-example').footable({
"columns": [
{ name: "nome",
title: "Nome"},
{ name: "credito_atual",
title: "Crédito Atual"},
{ name: "status",
title: "Status"}
],
"rows": $.get("index.json")
})};
my html
<table class="table" id="custom-ui-example" data-paging="true"></table>
Index.json should return array of objects, in your case it is returning object.
The format of the json should be
[{'id': '3'},{'id': '4'}]
Pagination seems to work fine.
Find the working fiddle here: https://jsfiddle.net/qwwjs7j3/
first of all, you should check if your json is valid. you can do that here for example: https://jsonformatter.curiousconcept.com/
then you can should make the get-call using:
$.get({
url: 'index.json'
}).done(function(data) {
data = JSON.parse(data);
});
the return data is hold in the data object of the callback function.

ng-repeat doesn't work on json array

I have this json array
[

{
Company: 
{
id: "19",
features_id: null,
features: "a:6:{i:1;s:1:"1";i:2;s:1:"2";i:3;s:1:"3";i:4;s:1:"0";i:5;s:1:"0";i:6;s:1:"6";}"
},
User: [ ]
},
-{
Company: 
{
id: "20",
features_id: null,
features: "a:6:{i:1;s:1:"1";i:2;s:1:"2";i:3;s:1:"3";i:4;s:1:"4";i:5;s:1:"5";i:6;s:1:"6";}"
},
User: 
[

{
id: "1",
group_id: "1",
type: null
}
]
}]
for somereason I cant get data into my div. Anyhelp will be appreciated. here is the jsfidler
http://jsfiddle.net/4Y9L3/
That JSON is not valid. Also, your template is not going to output anything visible unless you put some bind tags in the repeater like {{Company.Company.id}} for example.
You are using $.ajax(), so Angular doesn't know about it.
Use $http like this http://jsfiddle.net/4Y9L3/5/.

Categories