How to convert a string to object and loop in react - javascript

I have a object which I am getting from database
Note: The below array is the output of console.log(ansoptions);
[{id:1, option:"Yes"},{id:2, option:"No"},{id:3, option:"Other"}]
This initially is in datatype string. I want to convert it into array of objects and loop to get id and option values.
I have tried below code
var ansoptions = JSON.parse(JSON.stringify(props.answerOptions));
console.log(ansoptions);
Array.from(ansoptions, item => {
console.log(item);
})
For the console.log(item) I am getting the output as weird as below
[
{
i
d
:
1
,
o
p
and so on.....
How do I get it? Please help !!

Parse the JSON (a string), then just loop over the array that's created.
const json = '[{"id":1, "option":"Yes"},{"id":2, "option":"No"},{"id":3, "option":"Other"}]';
const arr = JSON.parse(json);
for (let obj of arr) {
console.log(obj.id, obj.option);
}

Related

Props name getting converted as object key

I have a data response of form:
claim_amount_arr: [218691.44]
claim_approval_status: ["In Process"]
percentages_claim: [1]
percentages_claim_amount: [1]
total_claim_arr: [2]
_id: 0
__proto__: Object
I want to convert it to array so as to map it into table further in a component. Since it does not have a key, I am not able to access it's key value pair for mapping.
I tried the following approach but then it eliminates all the key from the array:
const summary_props = this.props.summary
//console.log(summary_props); //this console gives me data as shown in image above
const sortedvalue = Object.keys(summary_props).map(key => {
return summary_props[key];
});
console.log(sortedvalue);
output of this console:
Please help.
class ClaimInformation()
{
constructor(data,index)
{
this.claim_amount = data.claim_amount_arr[index];
this.claim_approval_status = data.claim_approval_status[index];
this.percentage_claim = data.percentage_claim[index];
this.percentages_claim_amount = data.percentages_claim_amount[index];
this.total_claim = data.total_claim_arr[index];
}
}
var claims = [];
for(let i = 0; i < response.claim_amount_arr.length; i++){
claims.push(new ClaimInformation(response,i));
}
Try Object.entries().
In short, it can transform an object into an array.
Edit: More specific here
Object.entries(formData).map(([key, value]) => {
//Now you can access both the key and their value
})

How to merge multiple JSON objects to one single json object in javascript

My requirement is to get the json objects from different sources and merge them into one single json object using javascript
example:
Below there are 2 json objects with different values and I want to make it as one final Json object and append new value to the final result
json1= {
"b":"test1",
"a":"test3",
"type":"sample1"
}
json2= {
"endDate":"ddd1",
"startDate":"dd01"
}
Expected results should be like below
result = {
"b":"test1",
"a":"test3",
"type":"sample1",
"endDate":"ddd1",
"startDate":"dd01"
}
Can anyone suggest me the best way to achieve this in javascript please ?
You can use the rest operator to remove type property and then assign values from 1st object to new property of the merged object
let mergeObjects = (a, b) => {
let {type, ...rest} = b; //remove type property
for(let prop in rest){
if(a[prop]){
rest[prop].xyz = a[prop];
}
}
return rest;
}
let Object3= mergeObjects(Object1, Object2);
console.log(Object3);
Can be as simple as this:
let Object1 ={"b":"test1","a":"test3","type":"sample1"};let Object2 ={"b":{"endDate":"ddd1","startDate":"dd01"},"a":{"endDate":"31","startDate":"01"},"type":"sample2"}
let Object3 = Object2;
for (let i in Object3){
Object3[i]["XYZ"] = Object1[i]
}
Object3["type"] = "12345"
console.log(Object3)

Nested array formation with string in javascript

I have a string as "a.b.c.d:50" so i want to form an array with the above string as t[a][b][c][d]=50. so i have tried to split the code and form but this length of n values will generate dynamically. please let me know how we can achieve this.for fixed arrays i tried as below but not able to make this as for n number of arrays.
var str1="a.b.c.d:50";
var str=str1.split(":");
var dump=str[0].split(".");
t[dump[0]][dump[1]][dump[2]][dump[3]]=dump[4]
then result will be t[a][b][c][d]=50
You could take the JSON string, parse it and iterate all key/value pairs for a nested structure by saving the last key and crate new objects if not exist and assign the vlaue with the last property.
function setValue(object, path, value) {
var last = path.pop();
path.reduce((o, k) => o[k] = o[k] || {}, object)[last] = value;
}
var json = '{"subscriber.userTier.segment": "Red"}',
object = {};
Object
.entries(JSON.parse(json))
.forEach(([keys, value]) => setValue(object, keys.split('.'), value));
console.log(object);
Are you able to use ES6? This is something I just wrote quickly
var t = {a:{b:{c:{d:0}}}};
var str = "a.b.c.d:50"
var [chain, value] = str.split(':')
var parts = chain.split('.');
parts.slice(0, -1).reduce((c, v) => c[v], t)[parts[parts.length - 1]] = value;
console.log(t.a.b.c.d); // logs "50"
It works, however there is no error handling. If t['a']['b'] is undefined for example then you will get an uncaught TypeError, also if the string is in the incorrect format etc, it won't work.
At it's heart it uses reduce on the array ['a', 'b', 'c']. We pass t as the initial value for the reducer and then for each item in the array it does currentValue = currentValue[nextPart]. This will get you the object c, we then look at the last value in the parts array and set that property currentValue[lastPart] = value
That's a brief overview, hopefully you understand the rest of what's going on. If not feel free to ask :)
Quick and Dirty way of converting a string to a JSON object, if the string is constructed as a valid object.
var str = "a.b.c.d:50";
str = str.replace(/([a-z]){1}/gi, "\"$1\"");
str.split(".").forEach(function (value) {
str = str.replace(/\.(.*?)$/, ":{$1}");
});
var ar = JSON.parse("{"+str+"}");
console.log(ar);

How could I parse this json-string?

I have a string:
[{"data1":"A"},{"data2":"B"},{"data3":"C"}]
I used jQuery to convert this string to json:
test_json = $.parseJSON('[{"data1":"A"},{"data2":"B"},{"data3":"C"}]');
I got 3 objects:
I don't know, how could i get the key and value in this string-json?
Or the format of string-json is wrong?
have you tried cycle thorough the parsed array?
var test_json = $.parseJSON('[{"data1":"A"},{"data2":"B"},{"data3":"C"}]');
for(var a=0;a<test_json.length;a++) {
var obj = test_json[a];
for(var idx in obj) {
console.log(idx, obj[idx]);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
It has parsed the JSON correctly and returned an array of objects. You could do the following to access the first item containing { data1: "A" }:
console.log(tessst[0])

PUSH JSON items to array

I have this JSON string
{"Task": [Hours per Day],"Work": [11],"Eat": [6],"Commute": [4],"Sleep": [3]}
I want to push it's items to a jQuery array.
I already tried JSON.parse.
Normally I can push parameters like this:
MyArr.push(['Task','Hours per Day']);
MyArr.push(['Work','11']);
MyArr.push(['Eat','6']);
and so on.
How can I do the same with the JSON string?
Can you not just parse the JSON into an object and loop through?
var json = '{"Task": ["Hours per Day"],"Work": [11],"Eat": [6],"Commute": [4],"Sleep": [3]}'
var obj = JSON.parse(json);
MyArr = []
for (var key in obj) {
MyArr.push([key, obj[key][0]])
}
console.log(MyArr)

Categories

Resources