How to put multiple objects in one array in javascript? - javascript

How to put multiple objects in one array in javascript?
I have n json strings like this:
first object
'[{"name":"1","position":{"x":-28.890169060450745,"y":-89.45,"z":103.39384013230637},"property":{"floor":"Platform", "name":"1"}]'
second object
'[{"name":"2","position":{"x":-28.890169060450745,"y":-89.45,"z":103.39384013230637},"property":{"floor":"Platform", "name":"2"}]'
third object
'[{"name":"3","position":{"x":-28.890169060450745,"y":-89.45,"z":103.39384013230637},"property":{"floor":"Platform", "name":"3"}]'
...
nth object
Here I want to put n obejects into one result
like this
'[{"name":"1","position":{"x":-28.890169060450745,"y":-89.45,"z":103.39384013230637},"property":{"floor":"승강장","name":"1"},
[{"name":"2","position":{"x":-28.890169060450745,"y":-89.45,"z":103.39384013230637},"property":{"floor":"승강장","name":"2"}],
[{"name":"3","position":{"x":-28.890169060450745,"y":-89.45,"z":103.39384013230637},"property":{"floor":"승강장","name":"3"}]'
For this, I tried the following, but if I push it, it comes into the Array itself.
for (let i = 0; i < DataList.length; i++) {
if (i == 0) {
mergetData = JSON.parse(DataList[0]);
continue;
} else {
mergetData.push(JSON.parse(DataList[i]));
}
}
I am wondering how can I solve this problem.
Best Regards!

Parse all the JSON arrays, then concatenate them into a single array.
let parsedData = Datalist.map(s => JSON.parse(s));
let mergeData = [].concat(...parsedData);

Your are asking how to put multiple objects in one array but your desired output is the string object. So I'm considering your desired output as the actual question :)
For that you just have to iterate through your DataList and merge values into an string object.
StringObject = ''
for(let i=0; i < DataList.length; i++){
if(i===0)
StringObject += DataList[i]
else
StringObject += ',' + DataList[i]
}
console.log(StringObject)
Or just
StringObject = String(DataList)
console.log(StringObject)

Related

How to convert a converted string back into an array?

As far as I know, you can only save strings to local storage. So, I had to write a function so that I could save arrays. If I call console.log(fixA(["string1", [5, [false]], "string2"])); I get an output of "'string1',[5,[false]],'string2'". Here it is:
function fixA(array) {
var toreturn = "";
for (var i = 0; i < array.length; i++) {
if (typeof array[i] === 'object') {
toreturn += "[" + fixA(array[i]) + "]";
} else {
if (typeof array[i] === 'string') {
toreturn += "'" + array[i] + "'";
} else {
toreturn += array[i];
}
}
if (i < array.length - 1) {
toreturn += ",";
}
}
return toreturn;
}
console.log(fixA(["string1", [5, [false]], "string2"]));
The issue now is that I have no clue how to convert it back. I've tried a few things but have always gotten stuck on how I convert the arrays back. This is basically what I've tried:
function fixS(string) {
var toreturn = [];
var temp = string.split(",");
for (var i = 0; i < temp.length; i++) {
// I could run a check here to see if temp[i] starts with "[", but I'm not sure how to tell where the array ends.
// If it is an array, then I'd need to pass everything inside of the array back into fixS, making it recursive.
// The times I tried to do those two things above, I ran into the issue that the commas inside of the sub arrays also split everything, which I don't want (as the recursive function will deal with that).
toreturn.push(temp[i]);
}
return toreturn;
}
console.log(fixS("'string1',[5,[false]],'string2'"));
// This also doesn't return numbers as numbers or booleans as booleans.
Not much there, but it's as far as I've gotten. Any help is appreciated.
Instead of doing your own bespoke solution, unless you have something that can't be represented in JSON (your example can be), use JSON:
On page load:
var data = JSON.parse(localStorage.getItem("data") || "null");
if (!data) {
// There wasn't any, initialize
}
or
var data = JSON.parse(localStorage.getItem("data") || "{}");
...if you want a blank object if there is nothing in local storage.
When saving your data:
localStorage.setItem("data", JSON.stringify(data));
As David said there's JSON.stringify() & JSON.parse();
you can use those methods :
function save_to_storage(id, anything){
localStorage.setItem(id, JSON.stringify(anything));
}
function load_from_storage(id){
return JSON.parse(localStorage.getItem(id));
}
It can be achieved with help of JSON.stringify and JSON.parse functions.
Let me explore with help of code snippet.
var original_arr = ["string1", [5, [false]], "string2"]; // array
// Converting this array into string
var converted_str = JSON.stringify(original_arr); // converted into string
// Converting this string back to array
var new_arr = JSON.parse(converted_str ); // back to array
The other answers have already covered it, but note that P5.js also provides functionality for working, saving, and loading JSON directly.
Take a look at the saveJSON() and loadJSON() functions in the reference.

Get object out of multi dimensional array

I have three arrays filled with objects in JavaScript that I've put into a multi-dimensional array in order to get all possible combinations of all three objects to create a set of 'rules'. Then later in the code I want to be able to pull out the properties of these objects, but when I attempt to all I seem to be able to get is the string "[object]" and not the actual object itself.
This is how the array is put together:
var allArrays = [settings.serviceLevels, settings.serviceDays, settings.services];
function allPossibleCases(arr) {
if (arr.length === 1) {
return arr[0];
} else {
var result = [];
var allCasesOfRest = allPossibleCases(arr.slice(1));
for (var i = 0; i < allCasesOfRest.length; i++) {
for (var j = 0; j < arr[0].length; j++) {
result.push(arr[0][j] + allCasesOfRest[i]);
}
}
return result;
}
}
var uncheckedRules = allPossibleCases(allArrays);
I need to be able to get the properties out of settings.serviceLevels, settings.serviceDays and settings.services - I can find questions that do this with regular arrays but not with objects - is this even possible or have I taken it to a level where I've lost the properties?
Not sure I understood what you wanted. But here's a recursive function that will store in an array the properties of objects contained in another array :
function listProps(object, result) {
// for each property of the object :
for (objectProperty in object) {
// if it's an object, recursive call :
if (typeof object[objectProperty] === 'object') {
listProps(object[objectProperty], result);
} else { // otherwise, push it into the result array :
result.push(object[objectProperty]);
}
}
}
var allArrays = [settings.serviceLevels, settings.serviceDays, settings.services];
var result = [];
listProps(allArrays, result);
The result array should list every properties from the three objects settings.serviceLevels, settings.serviceDays, settings.services and their children (if they contain any object themselves).

Query regarding arrays

var arr=[1,2,3,[4,5],6,[7,8,9]],x,j;
for(x in arr)
for(j in arr[x])
console.log(arr[x][j]);
I want to print 1,2,3,...,9 but the above code prints 4,5,7,8,9.
I think "join" is enough:
console.log(arr.join());
If i understand your question correctly, you want to console to log 1 through 9. The way you currently have it, its only going to print the arrays within your array - that is why you are only getting 4,5,7,8,9.
What you could do is check to see if the value is an array in your first loop - if it is, iterate over it and print the values. If it is not, simply print the value.
if(arr[x].constructor === Array) {
//loop over the array and print out the values
for (j in arr[x]) {
console.log(arr[x][j])
}
} else {
//print out the plain value
console.log(arr[x])
}
Here is a pen to show the result: http://codepen.io/kyledodge/pen/zGwPBo
Another option is to use recursion. You could do something like this:
var printArrayValue = function(array) {
for (var i = 0; i < array.length; i++) {
if (array[i].constructor === Array) {
//if this an array, call this function again with the value
printArrayValue(array[i]);
} else {
//print the value
console.log(array[i]);
}
}
}
printArrayValue(arr);
Here is a pen to show the result: http://codepen.io/kyledodge/pen/VLbrPX
Coerce each element to array:
var arr=[1,2,3,[4,5],6,[7,8,9]],x,j;
for(x in arr) {
var arr2 = [].concat(arr[x]);
^^^^^^^^^^^^^^^^^
for(j in arr2)
console.log(arr2[j]);
}
This works because concat takes either an array or a single value.

iterating array of objects and the key values in JS

I have an array of objects
var j = [{"v1":["1","2","3"]}, {"v2":["4","5","6"]}, {"v3":["7","8","9"]}];
I want to check against the object property and perform some sort of logic. I am new to JS so I'm not sure of all the methods I have access to. Basically I want to compare the key value of the object to a string. If the key and the string are the same, then I would remove that object from the array. I'm not sure how to iterate through the object's key in the array.
var str = "v1";
for (var i in j) {
if (i.key == str) { // not sure how to access key value
j.splice(i,1);
}
}
Try this :
var j = [{"v1":["1","2","3"]}, {"v2":["4","5","6"]}, {"v3":["7","8","9"]}];
for (var i = 0; i < j.length; i++)
{
for (var k in j[i]) //do use this if you need to iterate
{
if (k === "mySomething")
{
//...do your stuff
}
}
}
Edit
less verbose :
for (var i = 0; i < j.length; i++)
{
if ("mySomething" in j[i])
{
//...do your stuff
}
}
As we've been discussing in comments, there is seldom a reason to use an array of objects that each only have one property (unless you're using the array to maintain a specific order), so I thought perhaps your problem might be easier if the data was structured like this:
var j = {"v1":["1","2","3"], "v2":["4","5","6"], "v3":["7","8","9"]};
And, you could then iterate it like this:
for (var key in j) {
console.log("j[" + key + "] = ", j[key]);
}
Working demo: http://jsfiddle.net/jfriend00/qdgzso1g/

For loop with array unexpected identifier

I have two arrays which im checking against in a for loop, but am stuck on how to make the for loop work on the array.
The array is build like this in json_encode:
var bdata = {"1":["50","50","0","Player1"],"2":["1500","1000","1000","Player2"]};
The array i am comparing it against is encoded like this:
var vdata = {"uid":"1","total":"1","w":"1","t":"1","s":"1","g":"1","l":"0","upd":"0"};
Then i tried to create the loop by converting them into arrays but it does not work:
bdata = JSON.parse(bdata);
vdata = JSON.parse(vdata);
for(bdata[0] as bid){
if(vdata["w"] >= bdata[bid][1] && vdata["g"] >= bdata[bid][0] && vdata["s"] >= bdata[bid][2]){
document.getElementById(id).innerHTML += "<br/>"+bdata[bid][3];
}else{
document.getElementById(id).innerHTML += "<br/><font color='red'>"+bdata[bid][3]+"</font>";
}
}
But the error i get is : Unexpected identifier
I'm not even sure im looping the first array correctly ?
Plenty of syntax errors. For example
For loop syntax. Either use
for (init counter; condition; post loop operation)
eg,
for (var i = 0; i < array.length; i++)
or
for (property in collection)
Greater-than-or-equal-to comparison operator
>=
not
=>
You don't need to use JSON.parse(), you already have JSON objects

Categories