How do I incrementally build and tear down a JavaScript object? - javascript

I need a user to be able to perform these actions:
Click an "Add" button. This will add a JavaScript object to either an array, or another JavaScript object.
Click a dynamic "Remove" button. This will remove the JavaScript object from the array, or object, whose ID matches the button click.
Submit the complete array, or object, of desired objects server-side for processing.
Using an array, am I able to get a handle via ID on a specific element and remove it with a "pop"-like function? If not, am I able to do so using a JavaScript object?
This question is related to this post, but there isn't much context in the original to answer my question. Thanks!

You can append an element to an array using the push method, like this:
var someArray = []; //Start with an empty array
//Later,
someArray.push({ name: 'value' });

It may actually be better to use an object rather than an array. This will allow you to name each object you send back to the server.
var dataObject = {};
function addData(name, data1, data2, data3) {
dataObject[name] = {
data1: data1,
data2: data2,
data3: data3
};
}
function removeData(name) {
delete dataObject[name];
}

Related

How to store key value pairs in JavaScript

I'm new to JavaScript and I want a Data Structure for my JavaScript code which stores Student data as key value pairs. The key is the student Registration number and the value is the students name.What I'm thinking is to create a JavaScript object as follows and store data as follows
let Student={
001A:"John",
002A:"Mathew"
};
Is this approach is correct? And if it is correct suppose a way to dynamically add key value pairs to that. Thank you
That would be an object literal. You'd want the key to be a string, but other than that you've basically got it. You can dynamically add properties using bracket syntax. I've attached a small snippet to give you an idea of how it works. :)
let Student={
"001A":"John",
"002A":"Mathew"
};
Student["003A"] = 'Jessica';
Object.entries(Student).forEach(entry => console.log(entry) );
The approach is correct. Given
const students={
'001A': 'John',
'002A': 'Mathew',
};
(Note: It's a good idea to keep your key as a string to prevent collisions with reserved keywords)
To read from the structure you can access the given record via
console.log(students['001A']); // => 'John'
To add new records dynamically, you just add a new property and assign it the desired value:
students['007'] = 'Ben';
which results in
console.log(students);
// =>
{
'001A': 'John',
'002A': 'Mathew',
'007': 'Ben',
};
To delete a given record you can do either
delete students['007'];
or
students['007'] = undefined;
The first option is a little "cleaner" as it completely deletes the given key, along with its assigned data.
Keep in mind that the data will be removed once you reload the page.

extracting a list of 2 property values

I have an object array:
user :[
{
name: String,
username: String
}
]
I want to view every change either to name or username.
I found underscore _.pluck only does the trick for one property (_.pluck(user, 'name')
Is there another way to have the list of both values?
With pluck you can only use one property, it simply isn't made to retrieve multiple. The method you would want to use is map, as suggested in this relevant question + answer: How to pluck multiple attributes from a Backbone collection?
Assuming you want the following output [['nameA','usernameA'],['nameB','usernameB'],...]], you could use map in the following manner:
var myResult = users.map(function(user) {
return [user.name, user.username];
});
NOTE: I changed the variable user to users to make more sense with your data.

Modifying array with asycronus data

I have a very curious problem that I'm sure someone in the world has figure out. Let's keep thing simple however. Ok, here we go.
So I have a plain array of objects. Let's say 5 objects for now.
[{id: 1, data: 'stuff'}, {id: 2, data: 'stuff'}, {id: 3, data: 'stuff'}, {id: 4, data: 'stuff'}, {id: 5, data: 'stuff'}]
What I then do is make 3 ajax requests which all, obviously, come back and different times. What I want to do is update this array based on the id's. For example I send off 3 ajax requests and receive new data for objects 1, 2 and 4. I'll need to update the data property in the respectives objects in the array. I'm using Array.splice to do the update. What I'm finding is that there are times, since the data comes in at different times, that things aren't updated correctly. I think this is because what splice does is actually remove the object from the array then re-inserts the new array in afterwards. It seems like there are instances when the splice method is in the middle of removing an object, then another response comes in and tries to remove another object, however, that object is not in the correct index, since the first object was removed and hasn't been inserted in yet. So the updating is off.
There's no reason you need to change the array at all, you are just trying to update objects within the array. Also, the index shouldn't matter because you are using the id property to uniquely identify each object, not the index in the array.
You should use whichever way is easiest for you to loop through the array, find the object with the corresponding id and update it.
This can be easily handled by looping over each object and keeping a reference to the object so that you can update each object as each request completes.
var promiseArr = dataArr.map(function (obj) {
return $http.get('/data/' + obj.id).then(function (result) {
obj.data = result.data;
});
});
// optional...
$q.all(promiseArr).then(function () {
console.log('all done!');
});

How can I add elements to a part of a json by using jquery

I try to add elements in a particular way to the following JSON:
var data = [{"name":"google",
"ip":"10.10.10.01",
"markets":[{"name":"spain","county":"6002,6017,6018,6019,6020"},
{"name":"france","county":"6003,6005,6006,6007,6008,6025,6026,6027,6028,6029"},
{"name":"japan","county":"6004,6021,6022,6023,6024"},
{"name":"korea","county":"6000,6013,6014,6015,6016"},
{"name":"vietnam","county":"6001,6009,6010,6011,6012"}]},
{"name":"amazon",
"ip":"10.10.10.02",
"markets":[{"name":"usa","county":"10000,10001,10002,10003,10004,10005"}]},
{"name":"yahoo",
"ip":"10.10.10.03",
"markets":[{"name":"japan","county":"10000"}]}];
I want to add this element to the json:
newData = [{"name":"amazon",
"ip":"10.10.10.02",
"markets":[{"name":"mexico","county":"9000"}]}];
The result might be exactly this:
var data = [{"name":"google",
"ip":"10.10.10.01",
"markets":[{"name":"spain","county":"6002,6017,6018,6019,6020"},
{"name":"france","county":"6003,6005,6006,6007,6008,6025,6026,6027,6028,6029"},
{"name":"japan","county":"6004,6021,6022,6023,6024"},
{"name":"korea","county":"6000,6013,6014,6015,6016"},
{"name":"vietnam","county":"6001,6009,6010,6011,6012"}]},
{"name":"amazon",
"ip":"10.10.10.02",
"markets":[{"name":"usa","county":"10000,10001,10002,10003,10004,10005"},
{"name":"mexico","county":"9000"}]},
{"name":"yahoo",
"ip":"10.10.10.03",
"markets":[{"name":"japan","county":"10000"}]}];
I tried to use :
$.extend(data.markets, newData)
$.extend(true, data, newData); //this works only in the case every element is new.
but nothing works the way I pretend.
Could anyone give me a solution?
Thanks in advance.
You haven't created JSON, you've created a JavaScript literal object.
You could add this particular piece of newdata by
data[1].markets.push({"name":"mexico","county":"9000"})
Because you are dealing with javascript objects, you can write a function to check for the existence of data[n] and push data.
You have an array of objects, where each object is like the following:
var item = {"name":"...",
"ip":"...",
"markets":[ /*some objects here*/];
}
So why not just creating your custom method to insert elements? It could search in the array if an item with the same name and ip exists, and then:
If it does exist: append the markets to the existing item markets attribute (maybe you need to check again if they already exist). UPDATE:The code that #jasonscript added in his answer will do the job: once you have found where to add the market, just add it to the array. Again, maybe you'll have to check if that market was already in the array. Using jQuery it will be: $.extend(true, data[i],newData)
If it doesn't exist: just add the item to the array: $.extend(true, data,newData)
Stealing a little code from another answer:
$.each(data, function(item){
if(item.name == newData[0].name && item.ip == newData[0].ip) {
item.markets.push.apply(item.markets, newData[0].markets);
}
}
This assumes that you know that all the market items in the new object are different to the existing ones - otherwise you'd have to do a nested foreach or something. If you can change the notation of the objects a little you could think about using a dictionary-like object for Markets to make that a little cleaner.
In fact, changing data from an associative array would probably work for that too. Then you could easily check for existence with:
if(data[myNewDataName]){
//add to markets
} else {
data[myNewDataName] = myNewData;
}

How to store temporary data at the client-side and then send it to the server

I need to store data temporarily at the client-side to allow users to add, edit or delete items without having to query the server for each of these actions; just when the user finishes adding items and clicks on the Add button, the list is sent to the server to be saved permanently.
This image describes what I want to achieve.
I know I have to use arrays in JavaScript, but I don't know how to create one to store objects (in this case Detail which contains :id, price and description).
I hope you can help me out.
Thanks in advance.
PS: I'm using JSP and... sorry for my English
Sure, since it's a table it makes sense to have an array of objects. Note that an object is surrounded by curly braces and an array is surrounded by brackets:
var myArray = []; // Initialize empty array
var myObject = {}; // Initialize empty object
This should accomplish what you need:
// Initialize variables
var newEntry, table = [];
// Create a new object
newEntry = {
id: '',
price: '',
description: ''
};
// Add the object to the end of the array
table.push(newEntry);
Which is the same as this:
// Initialize array
var table = [];
// Create object and add the object to the end of the array
table.push({
id: '22',
price: '$222',
description: 'Foo'
});
You can now access properties like this:
table[0].id; // '22'
On modern browsers, if you want the data to persist across sessions (like cookies) you could use the sessionStorage or localStorage objects.
When you want to send the data to the server, you'll send a JSON version of the table across the wire:
var data = JSON.stringify(table);
You can create an Array of your custom Detail objects pretty easily with object literals:
var details = [];
details.push({id:'abc1234', price:999.99, description:'Tesla Roadster'});
details.push({id:'xyz5678', price:129.99, description:'Land Rover'});
Then you can post your data to the server when the user clicks "Add."
Sounds like a good job for JSON.

Categories

Resources