Convert Form Data Array Object to JSON [duplicate] - html

This question already has answers here:
Convert JS object to JSON string
(23 answers)
Closed 1 year ago.
I'm trying to convert a form data object to JSON
var dataFormItin = $("#formitinerary").serializeArray();
result
itinerary: {
'itinerary[0][date]': undefined,
'itinerary[0][title]': 'Day 1 to Colombo',
'itinerary[0][destinationId]': '5ff3b8d7f0f3bf04b8141362',
'itinerary[0][program]': 'asd',
'itinerary[0][transfer_duration]': '2 hours'
}
and i want to make it like
itinerary : [
{ date : ..., title :...},
{ date : ..., title :...}
]

Maybe, it will be solved your problem
// 1. Example Data
const serializeArray = [
{ name: "itinerary[0][date]", value: "" },
{ name: "itinerary[0][title]", value: "Day 1 to Colombo" },
{ name: "itinerary[0][destinationId]", value: "5ff3b8d7f0f3bf04b8141362" },
{ name: "itinerary[0][program]", value: "asd" },
{ name: "itinerary[1][date]", value: "" },
{ name: "itinerary[1][title]", value: "Day 1 to Colombo" },
{ name: "itinerary[1][destinationId]", value: "5ff3b8d7f0f3bf04b8141362" },
{ name: "itinerary[1][program]", value: "asd" },
]
// 2. Define object key here
const arrayOfKey = ['date', 'title', 'destinationId', 'program']
// 3. Create empty array object
const arrayObject = []
// 4. Transform Serialize Array into Array Object
for(i = 0; i < serializeArray.length / arrayOfKey.length; i++ ){
const newObject = {}
for(const key of arrayOfKey){
newObject[key] = (serializeArray.find(data => data.name == `itinerary[${i}][${key}]`)).value
}
arrayObject.push(newObject)
}
// 5. Show the result
console.log(arrayObject)
/**
* [
{
date: '',
title: 'Day 1 to Colombo',
destinationId: '5ff3b8d7f0f3bf04b8141362',
program: 'asd'
},
{
date: '',
title: 'Day 1 to Colombo',
destinationId: '5ff3b8d7f0f3bf04b8141362',
program: 'asd'
}
]
*/

Related

jQuery array to splited json

Hello I have am trying to build a post request. Below is the format that I have to send
const data = {
categories: [
{
id: 9
},
{
id: 14
}
],
}
But what I have is ["29", "23", "22"] : these are category ids
Please help
You can use .map:
const arr = ["29", "23", "22"];
const data = {
categories: arr.map( e => ({ id: e }) )
};
console.log(data);

How to form a new object from a json as key value pair in Typescript?

I have a below json array of objects which have data of currency list.
[
{
id:"AUD",
value:"1.55"
},
{
id:"BGN",
value:"1.95"
},
{
id:"USD",
value:"1.17"
},
{
id:"CAD",
value:"1.51"
},
{
id:"EUR",
value:"1"
},
{
id:"INR",
value:"80.00"
}
]
I want to form a new array of object say newList with only currency value for USD, CAD and EUR. I can manually find the position of the object(eg: say item[3].value will give rate for CAD)and update the new object but I want to look for key values and get the values instead of getting index positions manually. How to do the same?
I hope this is what you expect.
This is your original list.
const list = [{ id: "AUD", value: "1.55" }, { id: "BGN", value: "1.95" }, { id: "USD", value: "1.17" }, { id: "CAD", value: "1.51" }, { id: "EUR", value: "1" }, { id: "INR", value: "80.00" }];
And this is how you can extract the wanted objects by comparison with their id.
const newList = list.filter(el => this.matches(el.id));
console.log(newList);
This method does the comparison for you and returns true when id matches. You can dynamically remove or add currencies.
private matches(id: string): boolean {
let match: boolean = false;
switch (id) {
case 'AUD':
match = true;
break;
case 'USD':
match = true;
break;
case 'EUR':
match = true;
break;
default:
match = false;
break;
}
return match;
}

Push value in one json to another json in angular

I have 2 different JSON object
JSON1
[
{
title: "Order Rule Violations",
type: "FieldView",
panel: "expanded",
data: [
{
label: "Rule Description",
type: "text",
},
{
label: "comments",
type: "inputarea",
},
],
},
]
JSON2
[
{
data: [
{
value: "00695",
},
{
value: " ",
},
],
},
]
I need to combine and get a result like
[
{
title: "Order Rule Violations",
type: "FieldView",
panel: "expanded",
data: [
{
label: "Rule Description",
type: "text",
value: "00695",
},
{
label: "comments",
type: "inputarea",
value: " ",
},
],
},
]
Please advise how can I achieve this using Angular / Typescript
This shall for this case:
for(var i=0;i<JSON1[0].data.length;i++)
JSON1[0].data[i].value= JSON2[0].data[i].value;
I altered JSON2 a little bit like JSON2 = ["","","",....] and the code below
worked for me ,
var k=0;
for(var i=0; i<this.JSON1.length; i++){
for(var j=0; j<this.JSON1[i].data.length; j++){
console.log("j",j);
this.JSON1[i].data[j].value = this.JSON2[k];
k++;
}
}
You can use use a nested Object.assign to iterate over each array and then merge the two objects.
const json1 = [{
title: 'Order Rule Violations',
type: 'FieldView',
panel: 'expanded',
data: [{
label: 'Rule Description',
type: 'text',
},
{
label: 'comments',
type: 'inputarea',
},
],
}];
const json2 = {
data: [{
value: '00695',
},
{
value: ' ',
},
]
};
const json3 = json1.map(y => {
y.data = y.data.map(
(x, index) => Object.assign(x, json2.data[index])
);
return y;
});
console.log(json3);
Another solution is to use Lodash's _.merge function

Nested arrays in object json to csv

Im using 'json-csv' library to create a csv from a users arrays with nested objects and arrays.
var users = [
{
subscriptions: [
{
package : {
name: 'Grammar'
},
state: 'EXPIRED',
timerange: {
period : 5550
},
transaction:{
amount: 10000
}
},
{
package : {
name: 'GK'
},
state: 'ACTIVE',
timerange: {
period : 30
},
transaction:{
amount: 10340
}
},
],
account:{
balance: 200
},
name: "Johhy Moe",
email: null,
user_id: "123456789",
username: null,
user_type: "facebook",
id: 3,
createdAt: "2016-07-11T08:02:40.000Z",
updatedAt: "2016-07-11T08:02:40.000Z",
},
{
subscriptions: [
{
package : {
name: 'GK'
},
state: 'EXPIRED',
timerange: {
period : 42
},
transaction:{
amount: 5252
}
},
{
package : {
name: 'MATH'
},
state: 'ACTIVE',
timerange: {
period : 25
},
transaction:{
amount: 200
}
}
],
account:{
balance: 1500
},
name: "John Doe",
email: null,
user_id: "123456789",
username: null,
user_type: "facebook",
id: 7,
createdAt: "2016-07-29T06:44:18.000Z",
updatedAt: "2016-07-29T06:44:18.000Z"
},
]
Now i want the generated csv to be like this
USERID,NAME,FBID,ACCOUNT,SUBSCRIPTION,PRICE,STATE,TIMEPERIOD
3,Johhy Moe,123456789,200,Grammar,10000,EXPIRED,5550
3,Johhy Moe,123456789,200,GK,10340,ACTIVE,30
7,John Doe,123456789,1500,GK,5252,EXPIRED,30
7,John Doe,123456789,1500,MATH,200,ACTIVE,25
As you see if there are two objects inside subscription array for each user, i want to repeat that user again but with different subscription data.
I've thought of using the library because my users array can go up to thousands of users with hundreds of subscription.
And i'm at a loss to what i should do.
my Code:
var options= {
fields : [
{
name : 'id',
label : 'USERID'
},
{
name : 'name',
label : 'Name'
},
{
name : 'user_id',
label : 'FBID'
},
{
name : 'account.balance',
label : 'ACCOUNT'
},
{
name: '',
label: 'Subscription'
}
]
}
var source = es.readArray(users)
source
.pipe(jsoncsv.csv(options))
.pipe(res)
I dont want to use a library also. So if someone could provide me with a resource to make my own csv file with strings and also using streams , that would be great. Thanks!!
This will solve your problem. Now you just have to change console.log to fs and write to your file.
var json2csv = function (json, listKeys) {
var str = "";
var prefix = "";
for (var i = 0; i < listKeys.length; i++) {
str += prefix + json[listKeys[i]];
prefix = ",";
}
return str;
};
var async = require('async');
var csvData = ['USERID,NAME,FBID,ACCOUNT,SUBSCRIPTION,PRICE,STATE,TIMEPERIOD'];
async.each(users, function (user, callback) {
var csvRow1 = {
USERID: user.id,
NAME: user.name,
FBID: user.user_id,
ACCOUNT: user.account.balance
};
async.each(user.subscriptions, function (subscription, callback) {
var csvRow2 = JSON.parse(JSON.stringify(csvRow1));
csvRow2.SUBSCRIPTION = subscription.package.name;
csvRow2.PRICE = subscription.transaction.amount;
csvRow2.STATE = subscription.state;
csvRow2.TIMEPERIOD = subscription.timerange.period;
csvData.push(json2csv(csvRow2, ['USERID', 'NAME', 'FBID', 'ACCOUNT', 'SUBSCRIPTION', 'PRICE', 'STATE', 'TIMEPERIOD']));
callback(null);
}, function (err) {
callback(err);
});
}, function (err) {
if (err) {
// return err;
} else {
// return csvData;
}
});

Json error - Cannot access child value on newtonsoft.json.linq.jproperty.

I have the following Json -
Property {
id: 122334,
source:
[ id : 123,
address:
{
city: "little rock",
state: "Arkansas",
country: "USA"
},
unit:
{
id: 222,
name: "The wall",
count: 2
}, ]
[ {id: 8889,
address:
{
city: "milka",
state: "Arkansas",
country: "USA"
},
unit:
{
id: 555,
name: "The watt",
count: 3
},
},
]
}
I am parsing it the following way -
string data = client.DownloadString(URL);
JToken token = JObject.Parse(data);
if (!string.IsNullOrEmpty(Convert.ToString(token["property"].Children())))
{
token["property"].Children().ToList().ForEach(child =>
{
string GetID = Convert.ToString(child["source"]["unit"]["id"]);
if (GetID == id)
{
//move rest of the code here
}
else
{
}
});
}
But I get the execption - cannot access child value on newtonsoft.json.linq.jproperty.
at the line -
string GetID = Convert.ToString(child["source"]["unit"]["id"]);
What am I doing wrong?
enter code here