Add an array to a json object in extjs - javascript

I wish to have an attribute called idField in my json object. Now this attribute is either an array if it contains multiple elements or just an object if it contains one element. I wish to create such an attribute from the data in an extjs store. In essence if the store contains just one element I need to insert this idField 'object' in the json object otherwise I need to insert an 'array' called idField in the json object. Please advise as to how to do that.
EDIT:
My store has 2 columns namely 'name' and 'type' in its data. What I wish is that if it contains just one element then my object should look like this:
{
...
idField : {
name : ...
type : ...
}
}
If my store contains 2 rows then my object should look like this :
{
...
idField : [
{
name : ...
type : ...
},
{
name : ...
type : ...
}
]
}
Also I have to INSERT this idField attribute inside the object. There is no currect idField attribute yet in the object.
EDIT 2:
I received this object in the console when I wrote console.log(Ext.getStore("My_store_name").data)

To get the data from the EXT JS store
var data = Ext.getStore("Your_Store_Name").data
In my snippet below I am assuming that you like to get the values from field name called item.
var data = Ext.getStore("Your_Store_Name").data
//imagine your JSON where you need to store is in variable myJSON
if (data.items.length == 1){
myJSON.idField = {type: 'sometype', name: data.item[0]} }
else if (data.item.length > 1)
{ //make an array of JSON
var list = [];
for(var i = 0; i < data.item.length; i++)
{
list.push({type: 'sometype', name: data.item[i]})
}
myJSON.idField = list; //set the array
}

Related

How do I programmatically build an object from my form data that includes arrays

I need to display some values on a jsp page, grab input from user and send it back to a controller that is using Jackson to bind it to my backing data object. Several rows that I display on the screen are backed by an array and are created with <c:forEach> and I'm generating a path like "blobs[0].id" and "blobs[0].text". When I try to put them into the json object to be sent back to the controller by an ajax call, they aren't being added to the object properly. The property name ends up having "[0]" in the name instead of representing the object at that array index.
<script>
var formData = {};
formData.blobs = [];
formData.blobs[0] = {};
formData.blobs[0].id = "English";
formData.blobs[0].text = "Hello";
formData["blobs[1].id"] = "German";
formData["blobs[1].text"] = "Guten Tag";
console.log(formData);
</script>
ends up looking like {blobs: [0 : {id: "English", text: "Hello"}], blobs[1].id: "German", blobs[1].text: "Guten Tag"} instead of
{blobs: [0 : {id: "English", text: "Hello"}, 1 : {id: "German", text: "Guten Tag"}]}
I am trying to assemble the model thusly:
<script>
function createModel() {
var form = $("#theForm");
var formData = {};
$.each(form, function(i, v){
var input = $(v);
if (input.attr("name")) {
formData[input.attr("name")] = input.val();
}
});
}
</script>
Accessing obj["attr"] is an option to access an object's attribute, so obj["attr[1][22]"] will access an attribute called "attr[1][22]", while accessing obj["attr"][1][22] will access the second element of obj.attr, and the second element's 22th element as well..
The solution will be to access formData["blobs"][0].id or even formData["blobs"][0]["id"]
you can format the string to your needs
$('#yourform').serializeArray() returns an array:
[
{"name":"foo","value":"1"},
{"name":"bar","value":"xxx"},
{"name":"this","value":"hi"}
]
$('#yourform').serialize() returns a string:
"foo=1&bar=xxx&this=hi"
so, in your case
var formData = {};
formData.blobs = [];
$('#yourform').serializeArray().forEach(function(blob){
formData.blobs.push({
id: blob.name,
text: blob.value
});
})

Automatically update JavaScript object property when another object's property is set

I have an array of objects, each containing a property named title.
The title property can hold one of two possible string values - "main" or "local". Only a single element in the array can have "main" as its title value at a given time, and the rest of the elements should have their title property set to "local".
For instance, take the following array:
var locations = [
{
title:"main",
place:"UK"
},
{
title:"local",
place:"USA"
},
{
title:"local",
place:"RUSSIA"
}
]
When setting the place:"USA" object's title property to "main", I want place:"UK" object's title property to automatically be set to "local".
How to achieve this with javascript?
One way to do this is set all title values to local, before setting desired object to main.
Another way is to remember which index is currently set to main and revert it to local when main is to be changed.
The following will return a copy of your array with the desired changes:
With ES6/Babel:
// Example:
somePlace = 'USA';
const newLocations = locations.map(l =>
{ ...l, title: l.place === somePlace ? 'main' : 'local' }
);
With Vanilla JS/Lodash:
// Example:
somePlace = 'USA';
var newLocations = _.map(locations, function (l) {
return _.assign({}, l, { title: l.place === somePlace ? 'main' : 'local' });
);
var newMainIndex = 2;
var locations = [
{
title:"main",
place:"UK"
},
{
title:"local",
place:"USA"
},
{
title:"local",
place:"RUSSIA"
}
];
for(var i=0, len=locations.length;i<len;i++){
locations[i].title = i === newMainIndex ? "main" : "local";
}

Get the value of differents attributes with localStorage.getItem()?

I am trying to create a little app, and I need to store some data.
I store them like this :
localStorage.setItem(taskID, taskTitle, taskTotal, taskActual, taskProgress);
(the taskID taskTitle, etc.. are values that I get from a form)
So this actually works well, and I have only one problem :
I can easily retrieve the taskID using:
for (i = 0; i < localStorage.length; i++) {
var taskID = "task-" + i;
};
but how can I retrieve the other values? Like if I want to retrieve taskActual value, how can I easily do that?
That's not how it works. Your code sets the value taskTitle under key taskID, the rest of arguments is discarded. Then you can only retrieve the taskTitle using localStorage.getItem( taskID ).
If you want to store more attributes you need to either store multiple items, for example:
var taskID = 'task-1';
localStorage.setItem(taskID +'-title', taskTitle);
localStorage.setItem(taskID +'-total', taskTotal);
// etc
// to retrieve:
var title = localStorage.getItem('task-1-title');
or store a serialized JSON:
var taskId = 'task-1', taskData = { title : 'task title', total : 'task total' /* etc.. */ };
// store
localStorage.setItem(taskID, JSON.stringify( taskData ) );
// retrieve
var task = JSON.parse( localStorage.getItem('task-1') );
// now you can use task.title, task.total etc
in local storage you are saving a key and a value. In this instance your 'keys' are the named items, i.e TaskId, taskTitle, etc. You need to have a corresponding value associated with the key. For example: localStorage.setItem('taskId',1); In this example, should you call localStorage.getItem('taskId'), the result would be 1, as it is it's corresponding value.

Store object inside object and update

I am trying to store an array inside and object like this:
var fieldData = {
checkedItem: {
fieldID : “1234”,
SelectedFields : []
}
checkedItem: {
fieldID : “12345”,
SelectedFields : []
}
}
I then want to also replace all selected fields to this object at a later stage.
I am a newbie to this so not sure how it would be done, I have tried everything I can think of!
The later changes to the object will referenced by fieldID.
I have tried stuff like:
fieldData["fieldID"] = selectedFieldSeq;
fieldData[selectedFieldSeq]["SelectedFields"] = $('#Tree').jqxTree('getCheckedItems');
$('#Tree').jqxTree('getCheckedItems');
returns an array of checked items on my tree.
This should do it:
'fieldID = $('#Tree').jqxTree('getCheckedItems');'
'fieldData.SelectedFields = fieldID'
There is a problem with this line :
fieldData[selectedFieldSeq]["SelectedFields"]
fieldData[selectedFieldSeq] is not defined, so it's return undefined
You need to initialize it before using it :
if (!fieldData[selectedFieldSeq]) {
fieldData[selectedFieldSeq] = {
SelectedFields : []
};
}
After, you can assign some value to SelectedFields.
Or did you want to simply do this : fieldData.SelectedFields = ...; ?

make json from table

I want to make specific json from table. I have a table, which has rows and 4 columns.
Here is my table I want to build an jsonarray from the table.
First value in the left column is key of json and last value in the right column is a valueof json.
I mean I want to get from table jsonarray, it must look as
json_from_form = [{color: 'id',
name: "mouse",
x: "table",
y: "book"}];
I have tried to build json, but have a problem with structure and setting a key in json object.
Please help me to buld right structure of json object.
var json_from_form_tmp = {};
$('#table').find('tbody tr').each(function (i) {
//var name = $(this).find('td:first').text();
json_from_form_tmp[i] = {
imd: $(this).find('td:eq(3) input').val()
};
});
console.log(json_from_form_tmp);
Here is my DEMO
You should use the jQuery map-function for this, here is an example:
$(function () {
var m = $("table tr").map(function (index, e) {
return {
color: $(e).children().eq(0).text(),
name: $(e).children().eq(1).text()
}
}).get();
});
Where m will be an array of objects as defined inside the map function.
To set a property of the object (json_from_form_tmp), use the ['propertyName'] notation.
//get the name of the property from the first column
var name = $(this).find('td:first').text();
//use that name as the name of the property. Your value fetch was right!
json_from_form_tmp[name] = $(this).find('td:eq(3) input').val();
Here is your fiddle with a tiny modification.
http://jsfiddle.net/bMzq8/32/

Categories

Resources