Initially I have variable that contains string data
var stringArray = "[{'middleName':'T','lastName':'TEST5LAST','occupation':'QA','homeAddressZipcode':'85001','entitySequenceNumber':7,'homeAddressCity':'PHOENIX','ssn':'111111115','cellPhone':'4807363273','employer':'ABC','workPhoneExtension':'5555','entityType':'JOINT','homePhone':'4807363272','identificationType':'0','email':'FIRST5.LAST5#TEST.COM','workPhone':'4807363274','firstName':'TEST5FIRST','homeAddressStreet':'8000','homeAddressState':'AZ'}]";
Is there a function in JavaScript or AngularJS that will allow me to build a real JavaScript Array like this?:
var realArray = [
{
"middleName":"T",
"lastName":"TEST1LAST",
"occupation":"HR",
...
},
{
"middleName":"T",
"lastName":"TEST5LAST",
"occupation":"QA",
...
},
...
];
Try this.
realArray = JSON.parse(stringArray);
JSON.parse(stringArray) return JSON object
Related
Hi I would like to check if there's a way to convert one of my JSON property's value from string to an array of string.
What I have:
const testJSON = {
"name": "Albert"
}
What I want:
const testJSON = {
"name": ["Albert"]
}
Many thanks for any help and direction I could explore!
You can give a try to this dynamic solution with the help of Object.keys() and Array.forEach() method.
const testJSON = {
"name": "Albert"
};
Object.keys(testJSON).forEach(key => {
testJSON[key] = [testJSON[key]]
});
console.log(testJSON);
You can assign new value which can be string or array to json property.
For example:
const testJSON = {
"name": "Albert"
}
// new array which we will assign to previous array property
const newArray = ["Albert", "John"];
// assigning new array to old json property
testJSON.name = newArray;
Don't think so, you only do maybe like the comment above
{name: [testJSON.name]}
if you have array, u can do .map for it
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 .
I have an array in my database that is being stored in the following format
["size:medium","height:10cm"]
this is problematic to display in a table.
Is there any way that I can convert this into a Javascript object or a JSON string like this?
{"size":"medium","height":"10cm"
}
p.s:i know json.stringfy,json_encode.the thing is they have stored key value pair as one string
You can build an object with the elements of the array and the left part as key and the right part as value of the by : separated strings.
array object
--------------------------- ---------------------------
[ -> {
"size:medium", -> size: "medium",
"height:10cm" -> height: "10cm"
] -> }
var array = ["size:medium", "height:10cm"],
object = array.reduce(function (r, a) {
var t = a.split(':');
r[t[0]] = t[1];
return r;
}, {});
document.write('<pre>' + JSON.stringify(object, 0, 4) + '</pre>');
You can try something like this:
Note: Following code will make array of objects. I don't think {["size:medium", "height:10cm"]} is a valid object
(function() {
var styleArr = ["size:medium", "height:10cm", "font-size: 18px"];
var resultObject = {};
styleArr.forEach(function(item) {
var values = item.replace(/\"/g, '').split(':');
resultObject[values[0]] = values[1];
});
console.log(resultObject)
})()
In Javascript you can use JSON.parse(), in order to convert your array in Javascript Object.
In PHP Use : json_encode(text)
In JavaScript : JSON.parse(text)
I am operating inside of a javascript for() loop and need to produce the following dynamically:
devCssFiles[ '../'+thisTheme._name+'/assets/css/main.css' ] =
'child_themes/'+thisTheme._name+'/master.less';
the intended result is an associative array that can be declared iteratively inside of a parent object, e.g. (thisTheme._name is declared in an external JSON file which is read when the code below is processed, this part is working fine)
var myConfigObj = {};
for ( var key in thisThemeMetaObj ) {
var devCssFiles = [],
devCssFiles[ '../'+thisTheme._name+'/assets/css/main.css' ] =
'child_themes/'+thisTheme._name+'/master.less';
myConfigObj[thisTheme._name] = devCssFiles;
}
I'm trying to give a complete explanation, but the problem is quite simple, I'm just declaring the named key of the associative array incorrectly at the line which reads devCssFiles[ '../'+thisTheme._name+'/assets/css/main.css' ] = 'child_themes/'+thisTheme._name+'/master.less';
Can someone show me the correct syntax here?
The intended output should be a JSON object like this:
myConfigObject: {
'../themeFoo/assets/css/main.css': [
'child_themes/themeFoo/master.less'
]
}
Syntax error was here:
var devCssFiles = [],
devCssFiles[ '../'+thisTheme._name+'/assets/css/main.css' ] =
'child_themes/'+thisTheme._name+'/master.less';
Problem being that devCssFiles = [] needs a semicolon (rather than a comma) so that the variable is in existence when the variable named property is declared. So it should be
var devCssFiles = [];
devCssFiles[ '../'+thisTheme._name+'/assets/css/main.css' ] =
'child_themes/'+thisTheme._name+'/master.less';
I think you want
var myConfigObj = {};
for ( var key in thisThemeMetaObj ) {
var thisTheme = thisThemeMetaObj[key],
devCssFiles = [ 'child_themes/'+thisTheme._name+'/master.less' ]; // array literal
myConfigObj['../'+thisTheme._name+'/assets/css/main.css'] = devCssFiles;
}
Notice that your devCssFiles was an array but you did create a non-numeric property on it.
I've got a JSON object that is structured like this:
{
"xaxis": [
"foo",
"bar",
"baz"
],
"yaxis": [
333,
992,
1365
]
}
From it I'd like to create another JSON object stuctured like this:
{
"piegraph": [
["foo",333],
["bar",992],
["baz",1365]
]
}
Doing this conversion in client-side JavaScript would save me additional development and another server round-trip to fetch what is essentially the same data.
I can employ the jQuery library if that would help.
You could use Functional JavaScript:
second = { piegraph: Functional.zip([first.xaxis, first.yaxis]) };
Assuming that your first JSON string is already parsed to an object, you just have to iterate over the elements of any of the two arrays, to build the result:
var result = { piegraph: [] }; // initialize piegraph as an empty array
var l = obj.xaxis.length;
while(l--) {
result.piegraph[l] = [ obj.xaxis[l], obj.yaxis[l] ];
}
// result will look like this:
// {"piegraph":[["foo",333],["bar",992],["baz",1365]]}
No libraries needed, just a plain sequential loop. ;)
Why can't you just use a for loop something like?
for(var i = 0; xaxis.length; i++){
piegraph.push({xaxis[i], yaxis[i]);
}
This isn't hard to do manually, but the underscore.js functional library has a bunch of very handy functions, including .zip():
var piegraph = _.zip( obj.xaxis, obj.yaxis );
Looks like you want to do pair-wise matching (aka "zipping") of two arrays.
Assume array1 and array2 for x and y axes and resultArray i.e. "piegraph"
jQuery.map(array1, function(item, i){
resultArray.push(new Array(array[item, array2[i]));
}
});