how to manipulate json objects in javascripts/jquery? [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I wanted to add delete update elements in json using jquery/javascript and when the file submit is done to the server wanted to consider the latest json object.
Can you suggest and approach i am stuck.

I use JSON.parse and JSON.stringify to manipulate.
json_flat = '{"page":"1","total":"2","ids":[{"id":"3085"},{"id":"3086"}]}'; // your flat json
json_object = JSON.parse(json_flat); //convert to an object
//Manipulation
json_object.page = "6"; //change values
delete json_object.total; //delete a value
json_flat = JSON.stringify(json_object); //convert back to flat
EDIT: Fixed some typos: JSFiddle

As mentioned, you can use jQuery's json functions to edit the object. Let me demonstrate how you might do this, with a little code:
let's take this JSON object:
{
"people":[
{"name":"Bob","score":9},
{"name":"Joe","score":6},
{"name":"Tom","score":7}
],
"projects":[
{"id":2347,"entries":5},
{"id":8563,"entries":3}
],
"lastUser":"Bob"
}
Now, let's say your server is storing that as a flat JSON file somewhere...what we'd do is load it on the client with jQuery's ajax methods, and edit it using a callback. After manipulating the object, we'll (for demonstration purposes) immediately send it back to a server-side script, which will presumably overwrite the current flat file:
$.getJSON(/*path to JSON file here*/,function(response){
response.lastUser="Tom"; //This is where the sample manipulation occurs.
$.post(/* path to server-side script*/,response,function(){
alert("Object Saved");
});
});
Hope that helps in understanding the pattern involved!

JSON data can be directly manipulated in javascript after parsing. (See Brad's comment on your question). To send the updated data back to server you can use $.post. Now, doesn't this solve your problem? If not, then please explain your problem in more detail.

Related

How to Get Unique Elements from a DOM Collection in Vanilla JavaScript ES6+ [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I have a JavaScript function that returns an array of Node or Element, but it contains duplicates. I searched around and found functions to get the unique items of an array, but it seems to work only on strings or simple types, when applying it to the DOM array, it does nothing. I assume it has to do with the items being objects.
Using ES6's Set as some answers suggest doesn't work. Another suggestion uses a filter function to check if the item already has an index in the array. Again, neither works for the DOM objects.
I'd appreciate it if someone could point to how I can remove the duplicates. Thanks in advance!
Update
#Kroltan seems to have understood what I mean, but for everyone else, here's a function that returns duplicate nodes:
function (
selector) {
const children = Array.from(this.parent().children).filter((
v) => v !== this);
if (!selector) {
return children;
}
return children.filter((
v) => v.matches && v.matches(selector));
}
If I were to do something like $("div"), I will get a lot of duplicates depending on nesting. I want to shrink the returned array of nodes to have no duplicates similar to how jQuery's implementation does it. Here's an example screenshot of my version (1) and jQuery's version (2). I want to get them to match.
Update 2
Figured it out. The Set solution works, but I was applying it to the wrong array and so I wasn't seeing the result I was expecting. Now that I'm applying it to the right array, it works, imagine that... :)
Those solutions do work. But they work on the principle of referential equality.
You're probably looking to remove structural duplicates, (e.g. a bunch of <br> elements or whatnot) that's trickier, and you'll have to decide on a criterion for their equality yourself. Something like Lodash's uniqBy. (check its source to see how it works!)

transmitting "[]" string to php driven backend [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
So theres a function which calls to backend which fetches all reservations in a certain timeframe and returns them to front-end. If there are no reservations in the respective timeframe, backend returns the string "[]". This data is then transmitted to backend again where I evaluate whether reservations exist or not.
For this, I want to use the php function "empty()" in backend.
And the code there basically just looks like this
$allReservationsOrRequestsByUser = json_decode($allReservationsOrRequestsByUser);
if(empty($allReservationsOrRequestsByUser)){
$overlapExists = false;
}else{
$overlapExists =
checkForOverlapWithExistingRequestsOrReservations($todayDate,
$allReservationsOrRequestsByUser);
}
echo $overlapExists;
Now, I tried the above code both with and without decoding it before the if-condition. In both cases, "empty()" function always returns false, which shouldn't be the case when the array actually was empty.
What am I doing wrong?
you are trying to check if "[]" as empty. So it isn't empty as a string... You can convert it to a proper array before checking with empty() like...
$a = "[]";
var_dump(empty($a));
var_dump(empty(json_decode($a)));
that returns,
bool(false) <- Without Json decode
bool(true) <- With Json decode
You need to check array data in array or object
e.g if fetched array contain
if(empty($allReservationsOrRequestsByUser[0]['name'])){
$overlapExists = false;
}else{
$overlapExists = checkForOverlapWithExistingRequestsOrReservations($todayDate,
$allReservationsOrRequestsByUser);
}
if object then use this and name is your database table column name
if(empty($allReservationsOrRequestsByUser[0]->name)){
$overlapExists = false;
}else{
$overlapExists = checkForOverlapWithExistingRequestsOrReservations($todayDate,
$allReservationsOrRequestsByUser);
}
echo $overlapExists;

Using innerHTML for partial HTML [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
the following function
<script>
function new_par()
{
var beginning="<input id=";
document.getElementById("debug").innerHTML=beginning;
}
</script>
produces no output, although if I remove the "<" sign, it does. Presumably the javascript avoids an output that would destroy the html page, but would there be anyway to force the output?
You're assigning it to a node's innerHTML property. When you plug the string into the DOM it's trying to parse it as though it were HTML. If you were to simply add it as a text node it would appear.
var beginning="<input id=''";
document.body.textContent = beginning;
https://jsfiddle.net/2patzyo1/
Edit: upon looking again at your question, if you are trying to get the input element to appear on the page, the string you're using isn't proper HTML because you never closed the tag. When the browser runs into it, it tries to parse and render it, but because it isn't valid it gives up. This will work:
var beginning="<input id=''>";
document.body.innerHTML = beginning;
https://jsfiddle.net/2patzyo1/1/

I want to seperate the PHP JSON string in jQuery [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have a problem with separating the json array result. When I alert the json result in jquery it returns me the following array.
{"productid":"17","product_quantity":"2"}{"productid":"9","product_quantity":"1"}
Now I want to separate every value in a different variable.
Thanx in advance.
that is not a valid json string.
first, you can convert the input to json string.
then, you can use JSON.parse to get the js array.
e.g.
first you need to do this:
input = '[{"productid":"17","product_quantity":"2"},{"productid":"9","product_quantity":"1"}]'
then:
input_array = JSON.parse(input)
It might be that your server returns a string that is not valid JSON. A valid example would be:
[{"productid":"17","product_quantity":"2"},{"productid":"9","product_quantity":"1"}]
How are you creating the json? Since you tagged PHP, the correct way (if you have an array) is like this, and it will return valid JSON, that you JS can handle:
echo json_encode($array);
The json you gave is misformed. I assume that's a typo.
Use JSON.parse to convert to a javascript object.
var jsonString = [{"productid":"17","product_quantity":"2"}, {"productid":"9","product_quantity":"1"}];
var data = JSON.parse(jsonString);
console.log(data[1].productid); // 9
But I do not know what you mean by."Now I want to separate every value in different variable."
Why?
Anyways you could do this. Though I do say dont. But you asked.
data.forEach(function(item){
window["productid"+item.productid] = item.product_quantity;
});
will give you 2 vars in global scope
console.log(productid17); // "2"
console.log(productid9); // "1"

pull a table from SQL to create javascript array? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have data like this in a SQL table:
ID | Word | Count
1 word1 10
2 word2 5
I'd like to request this data from javascript (or an aJax call I guess?) and have it create an array. I also don't care about the ID#, but just the word and it's 'count.' Then I guess it would be a 2d array to store this info? Ie, word[0][0] would return "word1" and word[0][1] would return 10. Maybe there's a better way to do that last part, though. And then I'd like to sort these by count.
Thoughts?
EDIT:
It would seem as though I have the data getting piped back via PHP to JSON. However, how the heck do I get the data out of JSON and into a JS array?
$.getJSON('php_file.php', function(response) {
// response is a JSON object that contains all the info from de sql query
/* do your JS stuff here */
})
It's saying that response is false, and no more. What's the deal?
Have a look at PHP's json_encode in the manual. It will allow you to convert a PHP array (which you'll populate from a database query) to a JSON object, which you will then output to the Ajax call from your Javascript.
Process:
Javascript calls e.g. results.php
results.php calls database and gets array
results.php uses json_encode on said array and outputs it to the browser (echo)
Javascript receives nice JSON array to use.
There's a nice example here:
https://stackoverflow.com/a/383664/2812842
The PHP file should look like this:
PHP_FILE.PHP
$sql = "SELECT * FROM table ORDER BY count [ASC|DESC]";
$result = execute_query($sql);
while($array = mysql_fetch_assoc($result));
echo json_encode($array);
And, then you have to make the AJAX call (for example, using JQuery)
$.getJSON('php_file.php', function(response) {
// response is a JSON object that contains all the info from de sql query
/* do your JS stuff here */
})

Categories

Resources