How to convert JSON array property value from arrays to keys - javascript

I am a beginner programmer trying to convert JSON array property value from arrays to keys.
From
..,"searchResult":[{"itemId":["123"],"title":["abc"],..}]
to
..,"searchResult":[{"itemId":"123","title":"abc",..}]
Full original JSON result here with search result highlighted
the JSON array is being received in this code
//function to retrieve JSON arrays
function _cb_findItemsByKeywords(root) {
//Navigates and assigns variable "items" into the property, item
var items = root.findItemsByKeywordsResponse[0].searchResult[0].item || [];
var a = (items);
//assigned variable a to the array
}
Question: How do I remove the square brackets and check my array a?
EDIT:
Sorry for the confusion, My goal is to combine this array with [..] with another array without [..] before appending the properties to a table.
My plan:

If I understand your question correctly, you wish to convert a JSON array into a Javascript object, since altering JSON property values to keys wouldn't be valid JSON.
To convert JSON array into Javascript object, in pure Javascript you do:
JSON.parse(yourJSONgoeshere);
Docs and examples here: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
Hope it helps.

Related

Issue passing MVC model array into javascript array

I'm trying to pass an array from my MVC Model into a javascript array (to use in fullCalendar), however having an issue.
From the below, "myArray" is being populated with the correct amount of items from the model array, but when I try to show obj.DateTime (valid field within the MVC model array) it returns undefined. The undefined alert appears the correct amount of times for items in the array.
Any help at all would be appreciated.
var myArray = [];
#foreach (var d in Model.Appointments)
{
#:myArray.push("#d");
}
myArray.forEach(function (obj) {
alert(obj.DateTime);
})
You can't use #d for converting your C# object to java-script object directly. You should encode your C# object to make a json value.
This code will encode (Serialize) your C# object to a JSON model.
#Html.Raw(Json.Encode(d));
Here is another question like yours

JSON / JavaScript get object keys

I'm extracting data from as follows -
The above function returns data in the below format -
[Object { date=Date, value=112, volume=1469}, Object { date=Date, value=124, volume=539}, Object { date=Date, value=114, volume=859}, Object { date=Date, value=123, volume=1284}, Object { date=Date, value=113, volume=1382}, Object { date=Date, value=129, volume=1353}]
I would like to obtain the list of keys only as a simple array.(Parsing the first object in the array is enough to get this as all other objects have the same keys) In case of the above output, I would like the simple array to look as ["date","value","volume"]
I tried JSON.stringify & then parse but it still doesn't work.
Also, how could I convert the whole array obtained from the chart into a simple array please?
I'm visualizing an output of the below type -
[{'date':'whatever', 'value':126, 'volume':911},
{'date':'whatever', 'value':136, 'volume':1005},
{'date':'whatever', 'value':125, 'volume':720}]
If the question doesn't make sense, please let me know. I'll see how best I could re-word.
Use Object.keys() function. Here in the response from function you get an array. Use that to get the list of keys.
var data = getChartData('param')
Object.keys(data[0]);

How do I attach JSON Stringify to a javascript variable

I have a variable :
var testData;
And I have a function that populates an array. Goes through an array and makes another array like so :
var person = {
"Name": obj.Name,
"Age": obj.Age,
}
partsObject.push(person);
I then want to make this array into JSON so I can use it with my D3 objects, so I do this :
testData = JSON.stringify(partsObject);
I can console log this variable, but when trying to go through it via D3's forEach method like so :
testData.forEach(function(d) // data is the JSON
{
I get the error Uncaught TypeError: testData.forEach is not a function
I don't understand how I can log the variable to the console yet it's as if I can't use it as JSON. Any ideas ?
As the name suggests stringify() converts a JavaScript object (the JSO in JSON) into a string of JSON. You can console.log() it because console.log expects to take a string, and anything that's not a string is converted to one to be displayed.
If you want to use it as an array again, you need to parse your string of JSON back to the JavaScript object: JSON.parse(testData).
You really dont need to stringify your Array to pass to d3. Do not to get confused with javascript objects, since forEach requires an array to loop through and you are passing a string to manipulate with forEach function
use:
partsObject.forEach(function(d)
{
...
JSON.stringify(partsObject); creates a string as"{'Name':'ABC','Age':23}"
Uncaught TypeError: testData.forEach is not a function caused because javascript was not able to find an Array
.stringify() turns a Javascript Object into a string. You would want to either run
partsObjects.forEach()
or alternativily you could turn the stringify'ed string back into an object with
(JSON.parse(testData)).forEach()
You are currently trying to loop through a String since you stringify your array.
Just do partsObject.forEach and don't stringify your Array.

How to get the correct array length

In my code i initialize array then put a value inside it why the output be 0 ?in spite of this should be 1
var changedfields=[];
changedfields['product']="productname";
alert(changedfields.length);
You're creating an associative array (normal arrays have an numeric index) but are actually trying to build a HashMap (a key, value pair). Use Objects or ES6 Maps.
I hope the following example will help you out:
var changedfields = {}; // create an object
changedfields['product']="productname";
var keys = Object.keys(changedfields); // returns the keys of the object ['product']
alert(keys.length);
I would suggest to read more about datastructures in javascript and avoid associative arrays in general.
Length of a JavaScript object (that is, associative array)
associative array versus object in javascript
Your question is interesting. Following is the answer.
First of all Arrays in Javascript are object type.
The first line you wrote creates an empty array and it's type is object.
var changedfields=[];
The second line you wrote creates a property called product of changedfields and sets the value to productname. It allows you add the product property because Javascript Array type is object. If you just had var changedfields; you could not add this property.
changedfields['product']="productname";
The third line you wrote simply finds the length of the empty array.
alert(changedfields.length);
In Javascript associative arrays are achieved using object. But if you want to add the product name in changedfields array. You could use push method like below and check the length:
changedfields.push('productname');
console.log(changedfields.length);
Javascript numerical indexed array length
So the Javascript numerical indexed array length can be calculated this way:
console.log(array.length);
console.log(changedfields.length); // in your case
The Javascript associative array length
The Javascript associative array (object) length can be calculated following ways:
Option 1:
Object.len = function(obj) {
var objLen = 0;
for (i in obj) {
obj.hasOwnProperty(i) ? objLen++ : '';
}
return objLen;
};
console.log(Object.len(changedfields));
Option 2:
console.log(Object.keys(array).length);
console.log(Object.keys(changedfields).length); // in your case
Note: This has issues with Internet Explorer 8, Opera etc

cant create array with STRING key

Im trying to create an associative array with objects, the key should always be a string (but they are always numbers).
This is how i store them (recording user clicks):
App.Recording[currentTime.toString()] = {sound: buttonName.toLowerCase() };
When trying to do this:
var save = {};
save.recording = App.Recording;
console.log(JSON.stringify(save));
I get this:
{"recording":[null, null,{"sound":"e"},null,null,null,.......,null,null,null,null,{"sound":"e"},....,null, null...]}
So, the toString() doesnt work on currentTime.toString(), which make my array store currentTime as numbers instead...
How can I save the objects and have an associative array?
Have a look HERE first. There are no associative arrays in JS. Instead of an array, you should use an object with a for in loop.

Categories