How to convert string into array of object? [duplicate] - javascript

This question already has answers here:
Best way to convert string to array of object in javascript?
(7 answers)
Closed 4 years ago.
let str="{SPOT:0,0:10,1:0},{SPOT:1,0:5,1:5}";
let result=[{"SPOT":0,"0":10,"1":0},{"SPOT":1,"0":5,"1":5}];
How to convert string to array of object

We can make it look like an array using template literals and a little bit of replace.
When it looks right we can use JSON.parse to actually turn it into an array
Now we have an array we can use forEach to go through each string and make them look like objects, we'll use replace again.
Once we've made each string look like an object we can push them into an empty results array, we'll have to make one outside of the loop.
Putting all this together looks a little like this:
const str = "{SPOT:0,0:10,1:0},{SPOT:1,0:5,1:5}";
let result = [];
JSON.parse(`["${str}"]`.replace(/},{/g, `}","{`)).forEach((e) => {
result.push(JSON.parse(e.replace(/{/g, `{"`).replace(/:/g, `":`).replace(/,/g, `,"`)));
});
console.log(result)
I hope you find this helpful.

Well this is not the best approach I would say but still, it will solve your problem:
let str = "{SPOT:0,0:10,1:0},{SPOT:1,0:5,1:5}";
let newStr = str.replace("},{", "}TempString{"); //append any dummy string in the existing one
let result = newStr.split("TempString");
console.log(result)

Related

Need to put this object into an array, how?

I need convert following in the EXACT format shown below with javascript, could you please suggest how to achieve this
from: {"healthy":true,"unhealthy_reasons":[]}
to: [{"healthy":true,"unhealthy_reasons":[]}]
If that's all you need to do, you can just wrap array brackets around the variable that contains the object:
let initialObject = {"healthy":true,"unhealthy_reasons":[]};
let arrayedObject = [initialObject];
But I'm wondering if there's more to this. If this is actually part of a more complicated task, just add that to your question and you'll get a more complete answer.
Use JSON.parse() and JSON.stringify()
let data = '{"healthy":true,"unhealthy_reasons":[]}';
let parsed = JSON.parse(data);
//TO get an array
console.log([parsed])
//TO get a string
console.log(JSON.stringify([parsed]))

How to filter array of objects and only return one result without the array brackets [duplicate]

This question already has answers here:
How to find first element of array matching a boolean condition in JavaScript?
(14 answers)
Closed 3 years ago.
I may not have had enough coffee on this lovely monday morning but there's something simple I'd like to do that is not coming to me.
I am filtering on an array of objects for an id:
const skuVariant = skuOptions.filter(sku => sku.itemNumber === variantItemNumber);
This returns an array that is of length 1 if there is a match.
The following line I have:
const skuVariantValueMap = skuVariant && skuVariant[0].varianceValueMap;
I would like to not have to check the for the first element of the array and instead only return the object from the call to filter and not the object inside an array.
To be extra clear skuVariant returns this: [{id: 1234}]
I would like it to return this: { id: 1234 }
This is possible using lodash utils but that's overkill. I am looking for something vanilla.
Is there an ES7, ES6 / super clean way of achieving this?
Thanks in advance.
Use Array.prototype.find instead of filter. It returns the value of the first element in the array that satisfies the provided testing function.

How to change data type in an array

I have an array obtained from a database that looks like this:
array1 = [Hello, Bye];
And not as I'd want:
array1 = ["Hello", "Bye"];
And so the compiler tells me that Hello and Bye are not defined. Is there any way of changing it without the need of changing the method to obtain it? It is a bit complex and I'd prefer editing it in the html file rather than changing the whole system. I've tried with String(array1) but it does not work. Any ideas? Thanks!
If i understand correctry, wrap your array variable as string with " or '
var string = "[Hello, Bye]";
string = string.replace(/(^\[)|(\]$)|(\s+)/g, '');
var array = string.split(',');
console.log(array);

JSON using parse or stringify correctly [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 8 years ago.
This is what I'm getting from server
['model':{"category":[{"id":1}],"food":[{"id":1}].... // long json here
How can I use jquery/javascript to parse to get category id and food id? I tried to use
JSON.parse(data)
or
JSON.stringify(data)
And after that, doing
$.each(data, function (i, x) {
it will give me each letter of all array. How can I parse it correctly, getting the ids that I want?
JSON.parse(data) will turn the data you showing into a JavaScript object, and there are a TON of ways to use the data from there. Example:
var parsedData = JSON.parse(data),
obj = {};
for(var key in parsedData['model']){
obj[key] = parsedData['model'][key]['id'];
}
Which would give you a resulting object of this:
{category:1, food:1}
This is based on the limited example of JSON you provided, the way you access it is entirely dependent on its structure. Hopefully this helps get you started, though.
You want to use JSON.parse(), but it returns the parsed object, so use it thusly:
var parsed = JSON.parse(data);
then work with parsed.

Converting a string to a multi-dimensional array

I have a nested for loop that creates a empty string value that represents a multidimensional array. Once the for loops have finished the result is something like this:
"[[0,0,0,0],[0,0,0,0]]"
I would like to add this to a multidimensional array within my code, how would i do this?
I have tried:
map = eval("[[0,0,0,0],[0,0,0,0]]");
but this does not produce the correct multidimensional array i am looking for.
I am looking to be able to use the array like this:
map[0][1] == 1;
Thanks
You could parse the string using JSON.parse() (MDN docu).
var str = "[[0,0,0,0],[0,0,0,0]]";
var map = JSON.parse( str );
However, in your example there is no entry equaling 1, so you requirement map[0][1] == 1 wont be fulfilled that way.

Categories

Resources