How to convert objects of array in to XML in Javascript - javascript

I have a data nested data structure or JSON, how can I convert that into an XML structure in Javascript.
[
{"loanId" : "LA00123", "MemberId" : "MI00123"},
{"loanId" : "LA001234", "MemberId" : "MI001234"}
]
Excepted result:
<result>
<loanID>LA00123</loanID>
<MemberId>MI00123</MemberId>
</result>
<result>
<loanID>LA001234</loanID>
<MemberId>MI001234</MemberId>
</result>

Simply by an iteration you can preapre the XML element first and the join by empty character.
Here Array.prototype.map() is used to make an iteration over the array and Array.prototype.join() is used to concatenate the prepared XML element to final result.
const data = [{"loanId" : "LA00123", "MemberId" : "MI00123"},{"loanId" : "LA001234", "MemberId" : "MI001234"}]
const result = data.map(obj => `<result><loanID>${obj.loanId}</loanID><MemberId>${obj.MemberId}</MemberId></result>`).join('')
console.log(result)

If you're converting data into XML as a string, you could perform reduce on the array:
let obj = [{
"loanId": "LA00123",
"MemberId": "MI00123"
},
{
"loanId": "LA001234",
"MemberId": "MI001234"
}
];
const toXml = (data) => {
return data.reduce((result, el) => {
return result + `<result><loadId>"${el.loanId}"</loadID><MemberId>${el.MemberId}</MemberId></result>\n`
}, '')
}
console.log(toXml(obj));
Creating XML object (overkill):
let obj = [{
"loanId": "LA00123",
"MemberId": "MI00123"
},
{
"loanId": "LA001234",
"MemberId": "MI001234"
}
];
let doc = document.implementation.createDocument(null, "myXML");
obj.forEach(a => {
let result = doc.createElement("result");
Object.entries(a).forEach(b => {
let node = doc.createElement(b[0]);
node.append(doc.createTextNode(b[1]));
result.append(node);
});
doc.documentElement.append(result);
});
console.log(new Array(...doc.documentElement.children).reduce((a, b) => a + new XMLSerializer().serializeToString(b), ''));

Related

how to convert nested array of objects to object of array

I have got array of nested array of objects .
const data = [ {group: [{label:"1"}]}, {topGroup: [{label:"2"}]} ]
I want to convert array to this format of objects and I want to get this output
let permission ={
group:["1"],
topGroup:["2"]
}
How can I do this ?
const data = [ {group: [{label:"1"}]}, {topGroup: [{label:"2"}]} ]
const converted = data.reduce((a,b) => {
const onlyKey = Object.keys(b)[0];
a[onlyKey] = b[onlyKey].map(i => i.label);
return a;
}, {})
console.log(converted)
const data = [ {group: [{label:"1"}]}, {topGroup: [{label:"2"}]} ]
let permission = {};
data.forEach(val =>{
for(prop in val){
permission[prop] = [val[prop][0]["label"]]
}
})
console.log(permission)
Give this a upvote if this is what you want.
Assuming the data is going to have labels as in that format forever, you could use something like that
const data = [{"group":[{"label":"1"}]},{"topGroup":[{"label":"12"}]}];
// The dict variable under here is the second parameter of reduce that I passed it `{}`.
// The ind variable is the data at the index of the array.
var newData = data.reduce(function(dict, ind){
// You basically get the keys and the values and put them in place
// and return the last state to the reduce function.
dict[Object.keys(ind)] = Object.values(ind)[0][0]["label"];
return dict;
}, {})
console.log(newData)
Use destructuring and Object.fromEntries.
const data = [{ group: [{ label: "1" }] }, { topGroup: [{ label: "2" }] }];
const permission = Object.fromEntries(
data.map(item => {
const [[key, [obj]]] = Object.entries(item);
return [key, Object.values(obj)];
})
);
console.log(permission);

How to convert url array query to object in Javascript

I have an URL with query params like this:
myLocalSite/?attributes%5B0%5D%5Bname%5D=customer_property_number&attributes%5B0%5D%5Bop%5D=equal&attributes%5B0%5D%5Bvalue%5D=12&attributes%5B1%5D%5Bname%5D=feedback_tags&attributes%5B1%5D%5Bop%5D=in&attributes%5B1%5D%5Bvalue%5D=test+1%2Cwww
after JSON parsing it convert into next structure
{
attributes[0][name]: "customer_property_number"
attributes[0][op]: "equal"
attributes[0][value]: "12"
attributes[1][name]: "feedback_tags"
attributes[1][op]: "in"
attributes[1][value]: "test 1,www"
}
In the end, I need an array that look like this:
attributes = [
{
name: 'customer_property_number',
op: 'equal',
value: '12',
},
{
name: 'feedback_tags',
op: 'in',
value: 'test 1, www',
},
]
Now does anyone know how I can then put these items into attributes array?
Thanks!
Here is the approach using URLSearchParams and going over each search param, parse and push to array of objects.
var sp = new URLSearchParams(
"myLocalSite/?attributes%5B0%5D%5Bname%5D=customer_property_number&attributes%5B0%5D%5Bop%5D=equal&attributes%5B0%5D%5Bvalue%5D=12&attributes%5B1%5D%5Bname%5D=feedback_tags&attributes%5B1%5D%5Bop%5D=in&attributes%5B1%5D%5Bvalue%5D=test+1%2Cwww"
);
var attributes = [];
for (entry of sp) {
const [attr, value] = entry;
const [index, key] = attr
.split("[")
.filter(x => x.includes("]"))
.map(x => x.slice(0, -1));
if (!attributes[Number(index)]) {
attributes[Number(index)] = {};
}
attributes[Number(index)][key] = value;
}
console.log(attributes);

Convert array of string to JAVASCRIPT object

I got problem, I've array of string as
[
"Time:25/10/2019 14:49:47.41,Server:Daniel.Europe.A…itical,Area:Europe,Site:,Station:Aberdeen,Stream:",
"Time:25/10/2019 14:49:48.16,Server:Daniel.Europe.U…,Area:Europe,Site:United Kingdom,Station:,Stream:"
]
I need to convert it to Object
[
{"Time" : "25/10/2019 14:49:47.41", "Server", "Daniel.Europe..", .. },
{}
]
likewise.
JSON.parse won't work on non-serialized string.
Using Object.fromEntries()
var data = [
"Time:25/10/2019 14:49:47.41,Server:Daniel.Europe.A…itical,Area:Europe,Site:,Station:Aberdeen,Stream:",
"Time:25/10/2019 14:49:48.16,Server:Daniel.Europe.U…,Area:Europe,Site:United Kingdom,Station:,Stream:"
]
var result = data.map(v =>
Object.fromEntries(v.split(',').map(v => v.split(/:(.*)/)))
)
console.log(result)
Something like this should work:
input.map(v => v.split(',').map(v => {
const [key, ...value] = v.split(':');
const obj = {};
obj[key] = value.join(':');
return obj;
}))
You can get it using map and reduce:
const arr = [
"Time:25/10/2019 14:49:47.41,Server:Daniel.Europe.A…itical,Area:Europe,Site:,Station:Aberdeen,Stream:",
"Time:25/10/2019 14:49:48.16,Server:Daniel.Europe.U…,Area:Europe,Site:United Kingdom,Station:,Stream:"
]
const newArr = arr.map(item => {
return item.split(",").reduce((acc, curr) => {
const label = curr.split(":")[0];
const value = curr.substring(label.length+1)
acc[curr.split(":")[0]] = value
return acc;
},{})
})
console.log(newArr)
You have to split your strings by commas and colons. Only problem is that your time string has a bunch of colons in it. Here is a start.
var a = [
"Time:25/10/2019 14:49:47.41,Server:Daniel.Europe.A…itical,Area:Europe,Site:,Station:Aberdeen,Stream:",
"Time:25/10/2019 14:49:48.16,Server:Daniel.Europe.U…,Area:Europe,Site:United Kingdom,Station:,Stream:"
];
b = a.map(function(line) {
var obj = {};
line.split(",").forEach(function(item) {
kv = item.split(/:(.+)/,2);
obj[kv[0]]=kv[1];
});
return obj;
});
console.log(b);

Get all Keys/Array keys in JSON parse Object?

I have sample JSON like this
`{
values:[{
"name": "Base Url",
"url": "https://kubemanagement-prod.kohls.com"
},
{
"name": "Base Url newwww",
"url": "https://batman.com"
}]
}`
Currently when I add this paticular JSON to the lodash _.keys gives me the result ["0", "1"] which is basically the index of first and second object 0 and 1.
What I exactly want is to retrieve all the keys of the JSON object including sub object properties as well. In this case ["values","0", "1","name","url"]
Does anyone knows a lodash method or a mechanism to retrieve all the keys given in complex JSON object to nth level?
language : Angular + Typescript
This function recursively gets the keys from an objects tree, using _.keys() and _.flatMap() and _.union() to combine lists of keys, and get only the unique values:
const getAllKeys = obj => _.union(
_.keys(obj),
_.flatMap(obj, o => _.isObject(o) ? getAllKeys(o) : [])
)
const arr = {"values": [{"name":"Base Url","url":"https://kubemanagement-prod.kohls.com"},{"name":"Base Url newwww","url":"https://batman.com"}]}
const result = getAllKeys(arr)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
And the same idea without lodash, using Object.values() and Array.flatMap() to iterate the current object (or array), and Array.concat() and a Set to make the keys unique:
const getAllKeys = obj => [...new Set([].concat(
Object.keys(obj),
Object.values(obj).flatMap(o => typeof o === 'object' ? getAllKeys(o) : [])
))]
const arr = {"values": [{"name":"Base Url","url":"https://kubemanagement-prod.kohls.com"},{"name":"Base Url newwww","url":"https://batman.com"}]}
const result = getAllKeys(arr)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
Without array indexes:
const getAllKeys = obj => _.union(
_.isArray(obj) ? [] : _.keys(obj),
_.flatMap(obj, o => _.isObject(o) ? getAllKeys(o) : [])
)
const arr = {"values": [{"name":"Base Url","url":"https://kubemanagement-prod.kohls.com"},{"name":"Base Url newwww","url":"https://batman.com"}]}
const result = getAllKeys(arr)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
You don't need lodash for this, Object.keys is sufficient. You just write a recursive function, writing to a Set, perhaps converting to array when you're done:
const array = [
{
"name": "Base Url",
"url": "https://kubemanagement-prod.kohls.com"
},
{
"name": "Base Url newwww",
"url": "https://batman.com"
}
];
function addAll(set, entries) {
for (const entry of entries) {
set.add(entry);
}
return set;
}
function allKeys(obj/*: object|array*/, keys/*: Set<string>*/ = new Set()) {
addAll(keys, Object.keys(obj));
for (const entry of Object.values(obj)) {
if (entry && typeof entry === "object") {
allKeys(entry, keys);
}
}
return keys;
}
console.log([...allKeys(array)]);
Or using the structure in your edit:
const array = {
values:[{
"name": "Base Url",
"url": "https://kubemanagement-prod.kohls.com"
},
{
"name": "Base Url newwww",
"url": "https://batman.com"
}]
}
function addAll(set, entries) {
for (const entry of entries) {
set.add(entry);
}
return set;
}
function allKeys(obj/*: object|array*/, keys/*: Set<string>*/ = new Set()) {
addAll(keys, Object.keys(obj));
for (const entry of Object.values(obj)) {
if (entry && typeof entry === "object") {
allKeys(entry, keys);
}
}
return keys;
}
console.log([...allKeys(array)]);
How about
const arr = {"values": [{"name":"Base Url","url":"https://kubemanagement-prod.kohls.com"},{"name":"Base Url newwww","url":"https://batman.com"}]}
let result1 = Object.keys(arr) // get the object keys which is "values"
let result2 = Object.keys(arr[result1]); // get the keys of the object name "0,1" here
let result3 = Object.keys(arr[result1][0]); // get property names of one object "name and url" here
let resutltant = result1.concat(result2, result3) // "merge array"
console.log(resutltant)
Assuming that your object properties names will remain constant
If you use typescript why don't use Object.entries or Object.values to do that?
You need to add to tsconfig the next line:
lib: [
......
"es2018",
]

Simple method to modify json keys casing to camelCase from snake_case

I have lots of json parsing and all the json I am receiving is having keys in snake case like user_name. And for parsing I need it in camel case like userName.
The sample json file would look like this:
[{
"user_id" : 1,
"user_name" : "Abcd"
},
{
"org_id" : 11,
"org_name" : "some_name"
}
...
]
Expected output:
[{
"userId" : 1,
"userName" : "Abcd"
},
{
"orgId" : 11,
"orgName" : "some_name"
}
...
]
The json I am receiving is not having any particular fixed notation and it can be anything. But all the keys will be in snake case. And I need to convert it to camelCase.
What I cannot do is, find and replace, because it also replace snake casing strings in values as well.
Is there any easy method, which can do the same?
You can use npm package called: camelcase-keys-deep
https://www.npmjs.com/package/camelcase-keys-deep
You can do the following:
var keys = [];//this will contain the json with desired output
for(var i = 0;i<myObj.length;i++)//myObj is the variable that contains your json
{
Object.keys(myObj[i]).forEach(function(key){
if(keys.indexOf(key) == -1)
{
var newValue = {};
var value = myObj[i][key];
key = key.replace(/_([a-z])/g, function (g) { return g[1].toUpperCase(); });
newValue[key] = value;
keys.push(newValue);
}
});
}
//console.log(keys);
Hope this helps :)
So AKSHAY JAIN's implementation is pretty solid but it will delete the properties that are not in snake case. I fixed the implementation.
var arr = [{
"user_id": 1,
"user_name": "Abcd"
},
{
"org_id": 11,
"org_name": "some_name"
},
{
"personId": 12,
"personName": "otherName"
}];
arr.forEach(a => {
Object.keys(a).forEach(k => {
newK = k.replace(/(\_\w)/g, (m) => m[1].toUpperCase());
if (newK != k) {
a[newK] = a[k];
delete a[k];
}
});
});
console.log(arr);
If u use lodash I would suggest my solution for this:
snake_case -> camelCase
function camelCaseDeep(anything) {
const thing = _.cloneDeep(anything);
if (
_.isEmpty(thing) ||
(!_.isObject(thing) && !_.isArray(thing))
) {
return thing;
}
if (_.isArray(thing)) {
const arr = thing;
return arr.map(el => camelCaseDeep(el))
}
// thing can be only not empty object here
const objWithMappedKeys = _.mapKeys(thing, (value, key) => _.camelCase(key));
const objWithMappedValues = _.mapValues(objWithMappedKeys, value => camelCaseDeep(value));
return objWithMappedValues;
}
camelCase -> snake_case
function snakeCaseDeep(anything) {
const thing = _.cloneDeep(anything);
if (
_.isEmpty(thing) ||
(!_.isObject(thing) && !_.isArray(thing))
) {
return thing;
}
if (_.isArray(thing)) {
const arr = thing;
return arr.map(el => snakeCaseDeep(el))
}
// thing can be only not empty object here
const objWithMappedKeys = _.mapKeys(thing, (value, key) => _.snakeCase(key));
const objWithMappedValues = _.mapValues(objWithMappedKeys, value => snakeCaseDeep(value));
return objWithMappedValues;
}
var arr = [{
"user_id": 1,
"user_name": "Abcd"
},
{
"org_id": 11,
"org_name": "some_name"
}
];
arr.forEach(a => {
Object.keys(a).forEach(k => {
newK = k.replace(/(\_\w)/g, (m) => m[1].toUpperCase());
a[newK] = a[k];
delete a[k];
});
});
console.log(arr);

Categories