What I am attempting to do is get unique values stored in the array and if a element gets pushed to the JSON string with the same MAC and IP I would like to make it replace the existing record with the new one it could replace it all or just the signal, distance and frequency I don't have a solid piece of code I am currently just experimenting trying to get what I need. Bellow is an example of the json output from my javascript console in chrome I know it's not formatted the best but it is valid.
{"prey":["{\"distance\": 8.686924173343307, \"signal\": \"-59\", \"frequency\": 2447, \"mac\": \"00:00:00:00:00:00\", \"ip\": \"192.168.43.27\"}"]}
What I have tried do far is use a for loop to check for duplicates this did not work as javascript was returning the wrong length of the array for some reason and it just got stuck in a infinite loop because I kept adding values to the array and it wasn't working in the unique way it should.
This is the code I currently have as I just keep hacking away at it trying everything I can think of this does not work in any way I have been playing with trying to get unique array but it just doesn't work the output of this is just the same as the actual output it does not get the unique array. I got the unique function from a stack overflow question
function arrayLastUnique(array) {
return array.filter(function (a, b, c) {
// keeps last occurrence
return c.indexOf(a, b + 1) < 0;
});
}
jsonSpy['prey'].push(msg);
$('#lines').append($('<p>').text(msg));
console.log(arrayLastUnique(jsonSpy.prey));
spyList = JSON.stringify(jsonSpy);
drawPositions(ctx, spyList);
var yourJSON = {"prey":
[
{ "distance": 8.686924173343307,
"signal": "-59",
"frequency": 2447,
"mac": "00:00:00:00:00:00",
"ip": "192.168.43.27"
}
]
};
var newDistance = 8.69;
if (yourJSON["prey"][0]["mac"] && yourJSON["prey"][0]["ip"]) {
yourJSON["prey"][0]["distance"] = newDistance;
}
If the values for "mac" and "ip" exist i.e. they are not an empty string, false, 0, null, undefined, the condition is satisfied. In the condition block you can assign a new value. This is just a very simple example. You have to adapt it and expand it according to your needs.
Related
I am working with data from an api that is returning values formatted like this for a few of the keys:
"key_one": [
"[\"Some Value One\",\"Some Value Two\",\"Some Value Three\"]"
],
"key_two": [
"[\"Some Value Four\",\"Some Value Five\"]"
],
The values of the keys come back as an array, but the array contains just one long string. I am looking for a way for taking THIS:
["[\"Some Value One\",\"Some Value Two\",\"Some Value Three\"]"]
and turning it into THIS:
["Some Value One","Some Value Two","Some Value Three"]
I have a feeling Regex would be best for this, but I am still a complete novice with Regex and my attempts so far havent gotten me anywhere.
I also attempted to do a basic for loop that looked for the presence of the " mark, and then checked to see if the character after wasnt a ',' and tried to push or += the letters into a string and then into an array at the end to return, but it was becoming a mess and wasn't working either.
I am hoping someone here can show me a more elegant solution.....
You ca try JSON.parse
const obj = {
"key_one": [
"[\"Some Value One\",\"Some Value Two\",\"Some Value Three\"]"
],
"key_two": [
"[\"Some Value Four\",\"Some Value Five\"]"
]
}
for (let keys in obj) {
obj[keys] = JSON.parse(obj[keys])
}
console.log(obj)
I have a building a chrome extension, I have following data as
var data = {}
data["Five, ok"] = "another one"
chrome.storage.sync.set(data)
chrome.storage.sync.get(function(content){console.log(content)})
>> {'Five, ok': "Another one ", 'ok, done': "New one"}
This can grow bigger with many values. (Key is a comma separated value).
I want to get all keys which include (2 different cases, this are user give values)
1. ok
2. done
this values are dynamic, what is the best way to achieve this in JavaScript/ jquery
chrome.storage.sync.get(function(content) {
var keys = Object.keys(content);
var keysOK = keys.filter(function(key){ return key.search(/\b(ok|done)\b/i) });
console.log(keysOK);
});
/\b(ok|done)\b/i finds the keys containing either ok or done
/\bok\b/i finds the keys containing ok
/\bdone\b/i finds the keys containing done
The i at the end makes the search case-insensitive.
As #charlietfl commented it's not efficient. However chrome.sync doesn't allow more than 100kB of data anyway so it's probably not an issue.
I have an array within my json output from a php file which uses the key 0,1,2 etc
I am having trouble accessing the key through javascript. I'm not sure what the issue is with using numbers. All the other data has a text value key which I can access using data.arrayname.key. To get around the issue I would like to set the key to a string with a number at the end so I can reference it back in javascript easily.
The array is pushed to each time in a loop. Within the loop I have tried
$NoOfTips++;
$jsonKey = 'Tip' + $NoOfTips;
$TBarray[$jsonKey]=$line;
array_push($TBarray);
In theory each time the loop goes round NoOfTips should increase by 1 which would also change the key to Tip1,Tip2,etc but obviously something is amiss. Could somebody please explain how why the Key is not being set correctly.
Thanks
To answer the real issue - to access a numeric index in javascript, you can't use dot notation, you would instead use brackets:
var data = { tips: { 1: "one", 2: "two" }, other: [1, { test: "tested" }] }
console.log(data.tips[1], data.other[0], data.other[1].test)
// output: one 1 tested
For the php side, when you do array_push, you have to specify the array you are pushing to, as well as what you are pushing:
array_push($TBarray, $line)
for example. I'm not sure what you are going for there, though.
I'm sending an array to the service
[
{
"toppingid": "ABB934CB-EAB7-4863-B832-7F533DA08E2F",
"toppingname": "Default",
"toppingprice": "0.000000"
}
]
When I console.log it shows as above. I do console.log as below
toppinglistforCart = [];
toppinglistforCart = request.body.toppinglist
console.log(toppinglistforCart);
But when I try to toppinglistforCart.length it returns 132 for some peculier reason.
and if I do console.log(toppinglistforCart[0]) then it returns [ very strange. Did someone else came through this same issue?
Thanks for your time
Your toppinglistforCart variable appears to be a string, with length 132. (It doesn't work in older IE, but) JS lets you use the topplinglistforCart[0] syntax to access individual characters within the string, similar to how the same syntax on an array accesses individual array items.
You need to parse the JSON content of your string to create an object:
toppinglistforCart = JSON.parse(request.body.toppinglist);
Note also that your first line:
toppinglistforCart = [];
...is not needed at all - it sets toppinglistforCart to a new empty array but then the next line sets toppinglistforCart to something else so that empty array gets thrown away.
I have a large array called "data".
At the 10th array position i have this at its data value:
[10] => 1,2
Now what im trying to do in JS is something like this:
i = 1;
if(i in data[10]){
//great success, very nice!
}
I thought comma separated data might act like an array with the "IN" method, but its not working. I get this error:
Uncaught TypeError: Cannot use 'in' operator to search for '1' in 1,2
What would be the correct solution for my problem ?
You don't show the code for how you assign 1,2 to data[10]. The value of 1,2 is simply 2 as you can see from executing the following in a JavaScript shell/console. See the reference for how the comma operator works.
However, the error message you are getting suggests that you have the string"1,2". To turn it into an array, you should use split() as in:
> data[10] = "1,2"
1,2
> data[10].split(',')
[ "1", "2" ]
To iterate over the values you can use the in operator on the resulting Array as in:
var data = new Array();
data[10] = '1,2';
var valueArray = data[10].split(',');
for (var i in valueArray) {
alert('valueArray[' + i + '] is ' + valueArray[i]);
}
You can run this in a browser console and the alert will show you two messages:
valueArray[0] is 1
valueArray[1] is 2
Note that you don't need to initialize i before the loop begins. The inoperator will do this automatically. Also, it's good practice to use local variables hence the var i in the code above.
On a side note, if you are new to JS but you need to deal with a lot of data structure manipulation, it's worth learning about underscore.js. Take a look at _.each() in particular. Underscore can save you from writing a lot of looping logic.
If, however, you want to do a membership check then you need to use not in but Array.indexOf(). See http://jsfiddle.net/nRS9m for an example forked from your jsfiddle in the comments. More examples:
> valueArray
[ "1", "2" ]
> valueArray.indexOf("3")
-1
> valueArray.indexOf("1")
0
> valueArray.indexOf("2")
1
> valueArray.indexOf(1)
-1
> valueArray.indexOf((1).toString())
0