json object shows value 1 - javascript

I am storing a json object in json array and assign it to another main json object, but when I print the value of main json object it display 1. Below is the code.
var jsonMainObject= {};
var jsonArray= [];
for(var j=0;j<cu.receivedData.length;j++) {
jsonMainObject["company"] = jsonArray.push(cu.receivedData[j].company);
}
console.log(jsonMainObject)
Below is the output
{ company: 1 }
But it should show the array. when i print jsonArray it shows the array of object, but when I console the output of jsonMainObject it displays the above output.

The push method returns the new length of the array. See documentation. I guess you should use:
jsonMainObject["company"].push(valueToPush)
or use concat (documentation)
jsonMainObject["company"] = jsonMainObject["company"].concat(valueToConcat)

There is no JSON at all here. JSON is a text format for representing data. What you have is a JavaScript object with a JavaScript array.
You are trying to put the array in the object at the same time as putting items in the array. The push method doesn't return the array that it was called on, it returns the length of the array. The company property will end up containing the length of the receivedData array.
You can put the array in the object from start:
var arr = [];
var mainObject = { company: arr };
for(var j = 0; j < cu.receivedData.length; j++) {
arr.push(cu.receivedData[j].company);
}
console.log(mainObject);

Related

Converting JSON value into JavaScript array

I want to convert a JSON string into a set of array containing the values from the JSON. after json.stringify(jsonmybe) and alert it display [{"role":"noi_user"},{"role":"bert_user"}] (which i saw as a JSON). I want to get the noi_user and bert_user and set them into a javascript array. something like ['noi_user','bert_user'] with quotes in each value.
I did the var stringy = json.parse() and the alert showing [object Object]. and further add this lines
for (var i = 0; i < stringy.length; i++) {
arr.push(stringy[i]['role']);}
and the arr I get was a value with comma when in alert but the comma missing as i display them in the text field and it becomes a long string like noi_userbert_user
What I really want is from [{"role":"noi_user"},{"role":"bert_user"}] to ['noi_user','bert_user']
Use JSON.parse and then reduce to get what you want,
var s = `[{"role":"noi_user"},{"role":"bert_user"}]`
var arr = []
try {
arr = JSON.parse(s).reduce((acc, val)=>[...acc, val.role], [])
} catch (e){
console.log("Invalid json")
}
console.log(arr)
Is this what you are loking for ? You can map on your array and just extract the role attribute of each datum.
const jsonString = ...
const data = JSON.parse(jsonString).map(data => data.role);
console.log(JSON.stringify(data, null, 2));
JSON uses double quotes to delimit strings and field names.
So you have a JSON string like
'[{"role":"noi_user"},{"role":"bert_user"}]'
You want to convert it to an object, then extract values of "role" fields of each element, put them all into an array.
Your example json string contains an array of user objects within "role" fields. Following code takes this list, loops through each user object and puts role's of each object into a separate array roleList.
var jsonStr = '[{"role":"noi_user"},{"role":"bert_user"}]';
var userObjList = JSON.parse(jsonStr);
var roleList = [];
userObjList.forEach(userObj => {
roleList.push(userObj.role);
});
console.log(roleList);
You could make a custom function to produce a sort of array_values in PHP but an indented and 2D level like so:
function array_values_indented (input) {
var tmpArr = []
for (key in input) {
tmpArr.push(input[key]['role']);
}
return tmpArr
}
var object = JSON.parse('[{"role":"noi_user"},{"role":"bert_user"}]');
var result = array_values_indented(object);
console.log(result);

function store array in array then return

var json = [];
var id = "displayImage1";
var object = "style";
storearray(id, object);
function storearray(_id, _object){
json.push(_id);
_id.push(_object);
return
}
i am making a function to store array inside a array then return it, here is my code , it didt work can anyone point out what i did wrong ? or show me how to make function then store array inside array.
so the array will be like this json -> id -> object
Demo
It looks like you're not looking for an array, but for an object, with the id as keys and the object as a value.
Is this what you're looking for?
var json = {};
json[id] = object
This would result in json containing {'displayImage1': 'style'}

Object properties are undefined after localStorage

I'm storing a bunch of values in localStorage. An array with JSON objects in it to be specific.
When I want to add another object to that array here is how I pull it, parse it, push onto the array and set it again.
var clickedItem = sessionStorage.getItem('location'),
interest = [],
interests = localStorage.getItem('interests');
interestsParsed = JSON.parse(interests);
interestsParsed.push(clickedItem);
localStorage.setItem('interests', JSON.stringify(interestsParsed));
Later on if I pull the array and loop through the array my properties are undefined.
var data = JSON.parse(localStorage.getItem('interests'));
for(var i = 0, j = data.length; i < j; i++ ){
console.log(data[i].anything); // any property is undefined
}
PS. The JSON object looks completely normal when I console it. Any ideas why the props would be undefined?
UPDATE:
data is in fact an array and looping through it does give me each value from within it. However each JSON object in the array is no longer an object and must be JSON.parsed to "recreate" an object out of the string that it is.
This was a really great lesson on storing JSON objects within an array in localStorage.
var data = JSON.parse(localStorage.getItem('interests'));
for(var i = 0, j = data.length; i < j; i++ ){
console.log(data[i].anything); // any property is undefined
var obj = JSON.parse(data[i]); // parse it instead
console.log(obj.title); // use it as an object now
}
My assumption is that you are trying to stringify a complex object, probably something like a DOM object or another built-in API's object. What happens is that JSON.stringify will strip the object out of all methods, and this includes internal setters and getters, and you remain with an empty (or almost empty) object.
My solution in such cases is to parse the complex object into a simple one containing only the properties you need in the formatting of your choosing.
JSON.parse() returns an object but you're treating it as an array. Instead of pushing to the array, add a new item to the object.
localStorage only supports strings. Use JSON.stringify() and JSON.parse().
//demo value
var clickedItem = {"testValue":111};
var interests = [{'a':1},{'b':2},{'c':4}];
localStorage.setItem('interests', JSON.stringify(interests));
//demo value end
interest = [],
interests = localStorage.getItem('interests');
interestsParsed = JSON.parse(interests);
interestsParsed.push(clickedItem);
console.log(interestsParsed);
localStorage.setItem('interests', JSON.stringify(interestsParsed));
var data = JSON.parse(localStorage.getItem('interests'));
for(var i = 0, j = data.length; i < j; i++ ){
console.log(data[i]);
}
I think you did't stringify value of interests,(before getting value at line no.3)

How to access multidimensional array by index in javascript?

I have an array like below in java-script
Result = [
{"ID":1,"Type":"Pyramid","Phase":"One"},
{"ID":2,"Type":"Pyramid","Phase":"Two"}
]
I tried accessing the individual values and was able to by the below code
alert(Result[0].ID) or alert(Result[0].Phase)
Is there a way to access this by index? like Result[0][1], i tried but getting [object][object]
also i need to access column count
Please help me
You have array of object and by using for loop you can easily access all element value.
try following
function getValue() {
var keys ;
var Result = [{"ID":1,"Type":"Pyramid","Phase":"One"}, {"ID":2,"Type":"Pyramid","Phase":"Two"}]
for(var i=0; i<Result.length;i++){
keys = [];
for(var k in Result[i]){
keys.push(k);
}
for(var k=0;k<keys.length;k++){
console.log(keys[k]+"="+ Result[i][keys[k]]);
}
console.log("key count =" +keys.length);
}
}
CHECK THIS
from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
alert(Result[0][Object.keys(Result[0])[0]]);
Result[0] gets the first row
Object.keys(Result[0]) gets the keys in the first row
Object.keys(Result[0])[0] gets the first column name.
Object.keys(Result[0]).length is the column count in the first row.
Also, objects are not indexed based on a linear integer index as arrays are, so assigning ordered numbers to the unordered list of keys is not right.
A two dimensional array would look like this:
Result = [
[1,"Pyramid","One"],
{2,"Pyramid","Two"}
]
in this case, you could address each field like so: Result[row][col] thus Result[0][2] would yield One.
To access fields in an array of object use the syntax you have provided. Also, why would you want to access the fields in your objects based on id? Or why would you not use an array of arrays?
Your Result is an array of object, then you must first get an object, and then get the property of your object. This is not a multidimensional array.
You array has an object we have to convert that object to array. So converting whole var Result to newResult you can access newResult and it's component through index number
Result = [
{"ID":1,"Type":"Pyramid","Phase":"One"},
{"ID":2,"Type":"Pyramid","Phase":"Two"}
];
var newResult = [];
for (var i = 0; i < Result.length; i++) {
newResult[i] = [];
for (var x in Result[i]) {
if (Result[i].hasOwnProperty(x)) {
newResult[i].push(Result[i][x]);
}
};
};
console.log(newResult);
Use newResult instead of Result
You can get ID by newResult[0][0]
http://jsfiddle.net/LLz1cbok/

Adding to JSON array in JavaScript/jQuery

I have data being pulled in from various sources, each returning some form of JSON or similar, although, differently formatted each time. I need to get them all into one array, but I can't figure out how to do it.
The first set is an array like this:
[
Object {id="70", type="ab", dateadded="12345678"},
Object {id="85", type="ab", dateadded="87654321"}, ... more items ...
]
The second set is being pulled in from Facebook, and is like this:
[
Object {id="12341234234", created_time="12345678"},
Object {id="567856785678", created_time="87654321"}, ... more items ...
]
So, I need to alter the second set so that it has 'type', and it has 'dateadded' instead of 'created_time', and then I need to get this all into one array so it can be sorted on 'dateadded'.
How can I do this?
Use the first array's push() method:
// for each item in second array
firstArray.push(convert(item));
function convert(obj) {
// Convert obj into format compatible with first array and return it
}
Hope this helps.
Assuming you have actual valid JSON instead of what you quoted above:
var jsonOld = '[{"id":"70","type":"ab","dateadded":"12345678"},{"id":"85","type":"ab","dateadded":"87654321"}]',
jsonNew = '[{"id":"12341234234","created_time":"12345678"},{"id":"567856785678","created_time":"87654321"}]';
Then first parse these values into actual Javascript arrays:
var mainArr = JSON.parse(jsonOld),
newArr = JSON.parse(jsonNew);
(If you already have actual Javascript arrays instead of JSON strings then skip the above step.)
Then just iterate over newArr and change the properties you need changed:
for (var i = 0, il = newArr.length; i < il; i++) {
newArr[i].type = 'ab';
newArr[i].dateadded = newArr[i].created_time;
delete newArr[i].created_time;
}
And concatenate newArr into mainArr:
mainArr = mainArr.concat(newArr);
And sort on dateadded:
mainArr.sort(function(a, b) { return a.dateadded - b.dateadded; });
This will result in:
[{"id":"70","type":"ab","dateadded":"12345678"},
{"id":"12341234234","type":"ab","dateadded":"12345678"},
{"id":"85","type":"ab","dateadded":"87654321"},
{"id":"567856785678","type":"ab","dateadded":"87654321"}]
See example

Categories