I have a multidimensional array that I am creating from a JSON Ajax call to my DB.
With in my Web App, I am trying to dynamically add a new row to the array using javascript along the lines of:
list[new_row_id].item_id = new_value ;
list[new_id].item_title = new_title ;
Clearly I am doing something wrong.
Any guidance would be appreciated.
Adding an element to the end of an array is done with the push-function:
array.push({"item_id": 10101, "item_title": "new title"});
If you meant "new_id" and "new_row_id" to be the same and it differs from an index starting from 0, because the keys are individual database keys, then you can solve it that way:
var any_db_id = 33;
var new_title = 'new title';
list[any_db_id] = {
item_id: any_db_id,
title: new_title
}
That will result in a JSON looking like that:
{
1: {
item_id: 1,
title: 'Entry coming from database 1'
},
5: {
item_id: 5,
title: 'Entry coming from database 2'
},
33: {
item_id: 33,
title: 'new title'
}
}
If the new_id and new_row_id are still same but it is actually just an index (each item has 0, 1, 2 and so on as key), then you should use the solution of Virendra Katariya.
Related
Lets say I have the following list in data:
data: {
todos: [
{ id: 1, title: "Learn Python" },
{ id: 2, title: "Learn JS" },
{ id: 3, title: "Create WebApp" }
]
}
Now I want to pass only the entry with id of 2 to the prop:
<dynamic-prop :id=todos[2] :title="todos.title"> </dynamic-prop>
Is something like that possible in Vue?
Sure, you can pass any data on. Just don't forget to add quotation marks and mind the off-by-one problem. So if you want to pass the second element in a (zero-indexed) array, you'd write something like:
<dynamic-prop :id="todos[1].id" :title="todos[1].title"> </dynamic-prop>
I have a JSON object(array) coming from a sharepoint table and I need to restructure the rows, but having a bit of a struggle (I'm fairly beginner in JS).
I have something like this:
[{'ID':'1', 'Title': 'First record', 'blue':'3', 'red':'6', 'yellow':'2'},
{'ID':'2', 'Title': 'Second record', 'blue':'1', 'red':'3', 'yellow':'6'}]
and I need to transform it into:
[{'ID':'1', 'Title': 'First record', 'category':'blue', 'count':'3'},
{'ID':'1', 'Title': 'First record', 'category':'red', 'count':'6'},
{'ID':'1', 'Title': 'First record', 'category':'yellow', 'count':'2'},
{'ID':'2', 'Title': 'Second record', 'category':'blue', 'count':'1'},
{'ID':'2', 'Title': 'Second record', 'category':'red', 'count':'3'},
{'ID':'2', 'Title': 'Second record', 'category':'yellow', 'count':'6'}]
What I'm trying to achieve:
Create separate rows to 'unlold' three category fields (blue, red, yellow), so one row becomes three
Preserve other fields in each newly created row (ID, Title)
I'm trying to reformat this data so that I can feed the array into Dimple/D3 chart to create a categorised chart showing value counts for each category.
I tried doing for...each and doing loops inside of loops and _.map from examples I've found, but not getting the output I'm after (debugging in browser is a pain, so not sure where the code fails for me :/ ). Would you be so kind as to show an example of how to do this manipulation properly (probably Underscore's .chain .each and .map)? Preferably without arrow functions (I need to make it work in IE11).
Thank you in advance!
It can be done by rebuilding new object collection; here is a sample;
var myData = JSON.parse('JsonString');
var transformedData = [];
myData.forEach(function(data){
transformedData.push({ ID: data.ID, Title: data.Title, category: "blue", count = data.blue });
transformedData.push({ ID: data.ID, Title: data.Title, category: "red", count = data.red });
transformedData.push({ ID: data.ID, Title: data.Title, category: "yellow", count = data.yellow });
});
var transformedJson = JSON.stringify(transformedData);
Remember JSON names should use double quotes " not single quotes '.
I'm making a project with PebbleJS.
i'm a noob and i'm learning little by little..so after recieving a JSON from a webpage and put all the data in localStorage objects, i want to put my variables in a UI.Menu Window, which is basically a JSON variable as you can see in example below:
var main = new UI.Menu({
sections: [{
items: [
{
title: 'street name a',
subtitle: 'ID 1121'
}, {
title: 'street name b',
subtitle: 'ID 1431'
}, {
title: 'street name c',
subtitle: 'ID 1907'
},{
title: 'street name d',
subtitle: 'ID 1002'
},{
title: 'street name e',
subtitle: 'ID 1330'
},
]
}]
});
i tried to make a loop cycle inside but gives me error...(pseudocode)
for (var x=0;x<10;x++)
{
title: localStorage.title+x,
subtitle: 'ID '+localStorage.title+x
}
i need to make this with no jQuery or other JS Frameworks, only pure javascript...
if i understand you question correctly, you want to create the data-structure from your first code example through a loop.
the data structure is a object with some properties and sub-objects like arrays. the structure just defines objects in your code. there is no json involved.
json is a subset of javascript which is used to interchange data-structures. it consists of plain text files with just javascript object declarations and is usually parsed to create a data-structure in memory. by declaring your data-structure in code there is no need to use an additional json-parsing step.
to setup the initial structure as above you would do:
var data = {
sections: [
{
items: []
}
]
}
than you would get the items array:
var items = data.sections[0].items
to this array you can add the items with your loop:
for ( var x = 0; x < 10; x++ ) {
var item = {
title: localStorage.title + x,
subtitle: 'ID ' + localStorage.title + x
};
items.push(item);
}
now you can build your UI.Menu with the data-object.
var main = new UI.Menu(data)
I struggled for hours trying to get this to work using Ember-Data with no result, so thought I give Ember-Model a try; still no joy.
I have the following:
App.Item = Ember.Model.extend({
itemName: Ember.attr(),
});
App.Strat = Ember.Model.extend({
stratName: Ember.attr(),
items: Ember.hasMany('App.Item',{key: 'items', embedded: true});
App.Strat.adapter = Ember.FixtureAdapter.create();
App.Strat.FIXTURES =
[
{id: 1, stratName: 's1', items:
[{id: 1, itemName: 'I1'}]},
{id: 2, stratName: 's2', items:
[{id: 2, itemName: 'I2'},
{id: 3, itemName: 'l3'}]}
];
Everything seemed to work fine up to this point. I'm able to display the fixture data via the templates. What I want to do is to allow the user to add additional strat records, by showing a pre-populated strat record on the screen, allowing users to make modifications, then save it with the two strat records loaded from the fixture data. I tried the following:
var dummyStrat =
{id: 100, stratName: "s5", items:
[{id: 101, itemName: "I5", strategy: 100}]};
var newStrat = App.Strat.create (dummyStrat);
newStrat.save();
This generated the following error:
TypeError: this.get(key).toJSON is not a function.
But no error if I did this:
var dummyStrat =
{id: 100, stratName: "s5"};
var newStrat = App.Strat.create (dummyStrat);
newStrat.save();
What am I doing wrong?
What happens if you remove strategy: 100 from the create call? I have pretty much the same code in my app except I'm not setting any variable that isn't already an attribute in my model.
My other suggestion would be to try renaming the items key to stratItems so that the key doesn't have the same name as the computed hasMany attribute.
I would like to generate this array in a JavaScript file
var sports = [{ id: 1, value: "Baseball" },
{ id: 2, value: "Soccer" },
{ id: 3, value: "Basketball" },
{ id: 4, value: "Volleyball" },
{ id: 5, value: "Tennis" },
{ id: 6, value: "Running" },
{ id: 7, value: "Swimming" },
{ id: 8, value: "Tournament"}];
I have started with:
var sports = db.Sports;
But now I am stuck on how to include this in a JavaScript file. Does .net have embedded JavaScript file like Rails do?
You'll need to just retrieve the data and serialize it into javascript. If those two are the only columns, you can do a straight serialization with JavaScriptSerializer or JSON.NET. If not, you'll need to convert them, maybe something like (using JSON.NET):
var x = db.Sports.Select(s => new { id = s.id, value = s.value }).ToArray();
string json = JsonConvert.SerializeObject(x);
Once you have this JSON string, you can dump it onto a page however you want, or write it directly to the response.
If you need to know a specific way to do this part, we'd need more details (WebForms or MVC, inside a page or a separate javascript resource, etc.)
EDIT:
Adding it to the view once it's in the ViewBag is straightforward. Inside your script on the view:
var sports = #Html.Raw(ViewBag.Sports);
// or if you're not using Razor:
var sports = <%= ViewBag.Sports %>;
Since ViewBag.Sports is already properly serialized, you don't need to worry about quotation marks or brackets.