i have this array obj:
var scenari =[
{pos:'i4y',azione:('persa','avanti','indietro'),'peso':(0.3,0.4,0.3)},
{pos:'g4r',azione:('persa','avanti','indietro'),'peso':(0.3,0.4,0.3)}
];
How to retrieve the array in key azione?
i try this but is print only 'indietro' and not array
console.log (scenari[0]['azione']);//indietro
Parentheses not define an array and must be use brackets ([]):
var scenari =[
{pos:'i4y',azione:['persa','avanti','indietro'],'peso':[0.3,0.4,0.3]},
{pos:'g4r',azione:['persa','avanti','indietro'],'peso':[0.3,0.4,0.3]}
];
console.log (scenari[0]['azione']);//indietro
You are using () instead of [].
If you use () last value will be the value of key
var scenari =[
{pos:'i4y',azione:['persa','avanti','indietro'],'peso':(0.3,0.4,0.3)},
{pos:'g4r',azione:['persa','avanti','indietro'],'peso':(0.3,0.4,0.3)}
];
console.log (scenari[0]['azione']);
//If you use ()
//Example:
var ke = ('d','e');
console.log(ke);
You are getting this issue because tuple javascript is treating the data in () as a expression, so to get the result in the way you want you have to use [] or convert your data in string .
Related
I have the below json object.
$scope.myDataList = [
{name:"one,two"},
{name:"three"},
{name:"four"},
{name:"five,eight,nine"}
]
I'm iterating the list and push the elements in the array as shown below.
$scope.myArray = new Array();
angular.forEach($scope.myDataList, function (value, key) {
$scope.myArray.push(value.name);
});
I want to push each element with comma spearated values also in the array.
example:
When I print $scope.myArray[0], it prints one,two.
But expected result is I want to print one for
$scope.myArray[0] and two for $scope.myArray[1], three for $scope.myArray[2].
Each value with comma separation also I want to push as an array element.
I tried as below but does not work.
var array = $scope.myArray.split(',');
Demo: http://plnkr.co/edit/q36BQeqsj5GVNkP4PPhq?p=preview
You need to split the name and concatenate the result to the array instead:
angular.forEach($scope.myDataList, function (value, key) {
$scope.myArray = $scope.myArray.concat(value.name.split(','));
});
Your problem has nothing to do with AngularJS, so I rewrote it in plain JavaScript:
$scope = {};
$scope.myDataList = [{name:"one,two"},{name:"three"},{name:"four"},{name:"five,eight,nine"}]
$scope.myArray = $scope.myDataList.map(({ name }) => name.split(','))
.reduce((result, splitElement) => result.concat(splitElement), []);
console.log($scope.myArray);
Note that the following line in your code
$scope.myArray.push(value.name);
pushes unsplit strings like 'five,eight,nine' into $scope.myArray. This is not what you want. Also, $scope.myArray.split(',') will fail, since Array.prototype has no split function.
One way to achieve the correct result is to map over the original array and split every element (the result is an array of string arrays). After that, you can join the inner string arrays together using Array.concat. This is what the following two lines do:
$scope.myArray = $scope.myDataList.map(({ name }) => name.split(','))
.reduce((result, splitElement) => result.concat(splitElement), []);
Here's a fairly simple means:
$scope.myArray = $scope.myDataList.reduce((a, {name}) => a.concat(name.split(',')), [])
Note that what you're trying to do is take the orginal list and create a new one. Since it's not a one-for-one mapping, it's not map. But reduce is appropriate, and carries more information than forEach.
const $scope = {
myDataList: [
{name:"one,two"},
{name:"three"},
{name:"four"},
{name:"five,eight,nine"}
]
}
$scope.myArray = $scope.myDataList.reduce((a, {name}) => a.concat(name.split(',')), [])
console.log($scope)
while pushing the array element you can do:
$scope.myArray = $scope.myArray.concat(value.name.split(","));
Here is the code to try.
http://plnkr.co/edit/nc91XI4vPJT0nEZvmMzU?p=preview
I have an array which is declared like this:
array = [];
and has values as shown below -
....
ChIJOaegwbTHwoARg7zN_9nq5Uc:"ChIJOaegwbTHwoARg7zN_9nq5Uc"
ChIJXTwCdefHwoAR9Jr4-le12q4:"ChIJXTwCdefHwoAR9Jr4-le12q4"
....
These values are printed when I do console.log(array);
When I try to do a JSON.stringify(array), it does not seem to work. I want to store this array in localStorage using localStorage.setItem().
I tried an example like in this in the browser console:
var arr=[]
arr[0] = 1
arr[1] = 2
JSON.stringify(arr);
And the above example worked perfectly fine.
Please provide your inputs, I have been stuck at this for hours.
You are trying to assign values in array like objects ; index can only be o,1,2 etc. not the strings like you have used. If you must do this, create an array of objects
the problem is that you are trying to set the array index as strings 'ChIJOaegwbTHwoARg7zN_9nq5Uc' and 'ChIJXTwCdefHwoAR9Jr4-le12q4' and although the browser seems to print it in the console, but array considers only integer keys as valid indices, so if you try to print array.length, it will print 0 and hence operations such as JSON.stringify(array) don't return you anything
var array = [];
array['ChIJOaegwbTHwoARg7zN_9nq5Uc'] = "ChIJOaegwbTHwoARg7zN_9nq5Uc";
array['ChIJXTwCdefHwoAR9Jr4-le12q4'] = "ChIJXTwCdefHwoAR9Jr4-le12q4";
console.log(array);
console.log(array.length)
What you need is not an array but an object
var obj = {};
obj['ChIJOaegwbTHwoARg7zN_9nq5Uc'] = "ChIJOaegwbTHwoARg7zN_9nq5Uc";
obj['ChIJXTwCdefHwoAR9Jr4-le12q4'] = "ChIJXTwCdefHwoAR9Jr4-le12q4";
console.log(obj);
console.log(JSON.stringify(obj))
That's not an array, but an object. Objects don't stringify as well as arrays do.
Basically:
String = 'This is a string'
Array = [
'This is a string',
'And so is this'
]
Object = {
firstString : 'This is a string',
secondString : 'And so is this.'
}
This works for me in a plunker.
let array = [];
array.push({"ChIJOaegwbTHwoARg7zN_9nq5Uc":"ChIJOaegwbTHwoARg7zN_9nq5Uc"});
array.push({"ChIJXTwCdefHwoAR9Jr4-le12q4":"ChIJXTwCdefHwoAR9Jr4-le12q4"});
console.log(JSON.stringify(array));
If you do a console.log(array), you should see something like this:
I am calling a third party web api, which returns data like this:
{"name":"Marine Lines","name":"jerry"}
I would like to convert this to a Json array, I could do a split by comma first and then by ":". but wondering if there are some better ways?
If the Web API return an object, then you can directly use dot-notation to access the value.
var x = {"name":"Marine Lines","name":"jerry"};
var name = x.name;
console.log(name);
Else if it is a string then you can parse it first using JSON.parse() and then do the same thing.
var x = '{"name":"Marine Lines","name":"jerry"}';
x = JSON.parse(x);
var name = x.name;
console.log(name);
First of all, your object has the name key twice, which means only the latter will be saved. As regards saving your object's values in an array, the following will do:
var
object = {"a": "Marine Lines", "b": "jerry"},
array = [];
/* Iterate over every enumerable property of the object. */
for (var key in object) {
/* Insert the value in the array. */
array[array.length] = object[key];
}
/* Log the created array. */
console.log(array);
I'm trying to parse out a single value from a URL String with three varaibles, and I am currently using the code:
var hash_array = location.hash.substring(1).split('&');
var hash_key_val = new Array(hash_array.length);
for (var i = 0; i < hash_array.length; i++) {
hash_key_val[i] = hash_array[i].split('=');
var array = hash_key_val[i];
console.log(array);
}
This code works to parse out the hash, but it creates separate arrays for each item and value like so:
["object1", "value1"]
["object2", "value2"]
["object3", "value3"]
By altering the array to var x = JSON.stringify(array[1]);
I can get the value which is all I need, but I only need the first value, while this code still returns:
"value1"
"value2"
"value3"
How can I alter the code so that the function only outputs value1?
Thanks!
Change the 1 for 0; Arrays start at zero index. Also I am not sure if you are aware that you are looping over the values as you are printing them out.
var arr = [
["object1", "value1"],
["object2", "value2"],
["object3", "value3"]
];
console.log(arr[0][1]);
As Arrow mentioned you need to change the index at which you access array from 1 to 0.
Additionally, why not use map:
var keys = hash_array.map(function(param){
return JSON.stringify(param.split('=')[0]);
}
with keys being ["object1", "object2", "object3"]
I'm getting output: [{"ref":"contact.html","score":0.7071067811865475}]
$.getJSON( "index.json", function(content) {
idx = lunr.Index.load(content);
var results = idx.search(variabletosearch);
var final = JSON.stringify(results);
console.log(final);
});
How can I print value of ref? When I console.log(final[0].ref); I get undefined.
EDIT:
JSON.stringify returns a string, not an object. So in this case 'final' is a string that contains the same data that was in the object 'results'
To access the data from an object, you can use result[0].ref, or if you want to use 'final' (although you don't need to), you can do this:
final = JSON.parse(final)
console.log(final[0].ref)
If it's only one object within the array, then the other answers are enough, but since arrays are used to store multiple objects, you can do this as follows:
var arr = [
{"ref": "object1", "score": "1"},
{"ref": "object2", "score": "2"}
]
arr.map(function(object) {
console.log(object.ref)
})
JSFiddle using an alert instead of console.log()
You can also use a loop, but this cleaner.
var a = [{"ref":"contact.html","score":0.7071067811865475}];
a[0].ref;
a[0] is the '0'th (or first) element in the array which is the object literal {"ref":"contact.html","score":0.7071067811865475} from here you can access the object normally using dot notation.
Expanded out a bit:
var a = [{"ref":"contact.html","score":0.7071067811865475}];
var myObject = a[0];
console.log(myObject.ref);
//or with null checking
if (myObject) {
console.log(myObject.ref ? myObject.ref : 'no value');
}
Well, assuming
var myvar = [{"ref":"contact.html","score":0.7071067811865475}];
then:
var myref = myvar[0].ref;