How to convert an array to object in this special case? - javascript

I am converting some data in order to send it to the frontend in a readable way.
I just convert some XML data into JSON, and I am getting an object, but every value is key : ['value'], and I need it key: 'value'
I am sending the data like this res.status(200).json({dealersData}); where dealersData returns this
{
"dealersData": [
{
"DealerId": [
"1"
],
"DealerName": [
"Carmen"
],
"NickName": [
"Carmen"
],
"Picture": [
"00001.jpg"
],
"Active": [
"1"
],
"LegalId": [
"111111111"
],
"TypeId": [
"1"
]
},
{
"DealerId": [
"14"
],
"DealerName": [
"Jaz"
],
"NickName": [
"Jaz"
],
"Active": [
"1"
],
"LegalId": [
"111111187"
],
"TypeId": [
"1"
]
}
]
}
so as you can see I am getting the data "TypeId":["1"] and so on, and I don't want like that, I want "TypeId" : 1, so what should I do to translate that arrays into objects hopefully using Lodash ?

For each dealer iterate over the keys and replace the value with value[0].
dealersData = dealersData.map( function( dealer ){
Object.keys( dealer ).forEach( function(key){
dealer[key] = dealer[key][0];
})
return dealer;
});
http://jsfiddle.net/r38u4qag/1/ (or ES2015 fat arrow version: http://jsfiddle.net/r38u4qag/2/)

This will recursively step through the object, changing arrays of length one to strings:
function process(obj) {
for(var key in obj) {
if(obj[key] instanceof Array && obj[key].length==1) {
obj[key]= obj[key][0];
}
else if(obj[key] instanceof Object) {
process(obj[key]);
}
}
} //process
function process(obj) {
for(var key in obj) {
if(obj[key] instanceof Array && obj[key].length==1) {
obj[key]= obj[key][0];
}
else if(obj[key] instanceof Object) {
process(obj[key]);
}
}
} //process
var obj= {
"dealersData": [
{
"DealerId": [
"1"
],
"DealerName": [
"Carmen"
],
"NickName": [
"Carmen"
],
"Picture": [
"00001.jpg"
],
"Active": [
"1"
],
"LegalId": [
"111111111"
],
"TypeId": [
"1"
]
},
{
"DealerId": [
"14"
],
"DealerName": [
"Jaz"
],
"NickName": [
"Jaz"
],
"Active": [
"1"
],
"LegalId": [
"111111187"
],
"TypeId": [
"1"
]
}
]
}
process(obj);
document.querySelector('pre').innerHTML= JSON.stringify(obj,'\n',2);
<pre></pre>

If I get it right, you have arrays, but you don't need them, since you will always return just a single value, right?
If that's the case, you just have to call .toString() method on your arrays object. I would iterate over your dealersData to do that on all arrays:
for(var i = 0; i < dealersData.length; i++) {
dealersData[i].DealerId = dealersData[i].DealerId.toString();
dealersData[i].DealerName = dealersData[i].DealerName.toString();
[...]
}

Related

How to conditionally sort and right shift a JSON array?

I have a JSON array as follows :
[{
"name": "ABC",
"default": false,
"details": [
{
"detail1": "value1"
},
{
"detail2": "value2"
}
]
},
{
"name": "PQR",
"default": false,
"details": [
{
"detail3": "value3"
},
{
"detail4": "value4"
}
]
},
{
"name": "XYZ",
"default": true,
"details": [
{
"detail5": "value5"
},
{
"detail6": "value6"
}
]
}]
Now if the default value is true , I want it to be the first element of the array and rest of the elements should be sorted alphabetically based on the name . Only one of the element will have default as true or all the elements will have default as false.
The expected JSON after sorting should be :
[{
"name": "XYZ",
"default": true,
"details": [
{
"detail5": "value5"
},
{
"detail6": "value6"
}
]
},
{
"name": "ABC",
"default": false,
"details": [
{
"detail1": "value1"
},
{
"detail2": "value2"
}
]
},
{
"name": "PQR",
"default": false,
"details": [
{
"detail3": "value3"
},
{
"detail4": "value4"
}
]
}]
I have tried this code for sorting the JSON array :
jsonArray.sort( function( a, b ) {
a = a.name.toLowerCase();
b = b.name.toLowerCase();
return a < b ? -1 : a > b ? 1 : 0;
});
But I am not able to figure out how to check for the default value and sort accordingly. How do I achieve the expected result?
You're on the right way. Just modify the function to include the check for default:
jsonArray.sort( function( a, b ) {
const name1 = a.name.toLowerCase();
const name2 = b.name.toLowerCase();
return (b.default - a.default) || ((name1 > name2) - (name2 > name1))
});
I've got the quick code for string comparison from here: https://stackoverflow.com/a/17765169/2244262

Returning parent key based on a value in a list of arrays in Javascript

{
"arr1":[
{
"name":"something1",
"id":"233111f4-9126-490d-a78b-1724009fa484"
},
{
"name":"something2",
"id":"50584c03-ac71-4225-9c6a-d12bcc542951"
},
{
"name":"Unique",
"id":"43cf14ee58ea4d8da43e9a2f208d215c"
},
{
"name":"something4",
"id":"ce0374ba-6d9b-4ff5-98b1-1191d1d2a9a7"
},
{
"name":"something5",
"id":"ef825dc3-003c-4740-955a-bb437cfb4199"
}
],
"arr2":
[
{
"name":"Unique",
"id":"43cf14ee58ea4d8da43e9a2f208d215c"}
]
}
This is list of arrays with keys and values as array, I want to return all the keys based on a particular value;
For Eg:
I want to return the parent keys which are [arr1,arr2], reason being both the arrays contain a value Unique, So I want to return the parent key of both the values, which is arr1 and arr2 respectively.
Note: The list can have n numbers of arrays.
Any help would be appreciated. Thanks in advance.
The simplest way to go about this is:
Loop through the keys in your object
Check if the array contains any objects with the name "Unique"
If so, add the objects key to an array
const obj = {
"arr1": [{ "name": "something1", "id": "233111f4-9126-490d-a78b-1724009fa484" }, { "name": "something2", "id": "50584c03-ac71-4225-9c6a-d12bcc542951" }, { "name": "Unique", "id": "43cf14ee58ea4d8da43e9a2f208d215c" }, { "name": "something4", "id": "ce0374ba-6d9b-4ff5-98b1-1191d1d2a9a7" }, { "name": "something5", "id": "ef825dc3-003c-4740-955a-bb437cfb4199" }],
"arr2": [{ "name": "Unique", "id": "43cf14ee58ea4d8da43e9a2f208d215c" }],
"arr3": [{ "name": "No unique here","id": "Example" }]
}
// Create our array that will contain the keys
const keys = []
// Loop through each key in the object
for (const prop in obj) {
// Use .some to see if any of the objects in this array have the selected name
const containsUnique = obj[prop].some(o => o.name === 'Unique')
if (containsUnique) {
// Add the current key to the array
keys.push(prop)
}
}
// Use the array of keys which contain an object named "Unique"
console.log(keys)
This is a more generic approach:
const getKeysByValue = (data, value) => {
const dataKeys = Object.keys(data);
const valueKey = Object.keys(value);
return dataKeys.filter(currKey => {
for(let element of data[currKey])
if(element[valueKey] === value[valueKey])
return true;
});
}
const data = {
"arr1":[
{
"name":"something1",
"shape": "Trapezium",
"id":"233111f4-9126-490d-a78b-1724009fa484"
},
{
"name":"something2",
"shape": "Octagon",
"id":"50584c03-ac71-4225-9c6a-d12bcc542951"
},
{
"name":"Unique",
"shape": "Square",
"id":"43cf14ee58ea4d8da43e9a2f208d215c"
},
{
"name":"something4",
"shape": "Triangle",
"id":"ce0374ba-6d9b-4ff5-98b1-1191d1d2a9a7"
},
{
"name":"something5",
"shape": "Circle",
"id":"ef825dc3-003c-4740-955a-bb437cfb4199"
}
],
"arr2":
[
{
"name":"Unique",
"shape": "Triangle",
"id":"43cf14ee58ea4d8da43e9a2f208d215c"
}
],
"arr3":
[
{
"name":"Not-Unique",
"shape": "Circle",
"id":"8hcf14ee58ea25g343e9a2f208df215c"
}
]
}
console.log(getKeysByValue(data, {"name": "something2"})); // ["arr1"]
console.log(getKeysByValue(data, {"name": "Unique"})); // ["arr1", "arr2"]
console.log(getKeysByValue(data, {"shape": "Circle"})); // ["arr1", "arr3"]
console.log(getKeysByValue(data, {"shape": "Square"})); // ["arr1"]
The function receives two parameters, data and value. value is expected to be in the format of the value you are looking to filter with. In your example you wanted it to be "Unique" and in each object in the array it was presented like "name": "Unique" so we will send it as an object, {"name": "Unique"}.
In this way you can have different value to filter with. In the example above I added a shape key and value to each element, we can filter by this value too as shown in the example above.
you can do like this :
const obj = {
"arr1": [{ "name": "something1", "id": "233111f4-9126-490d-a78b-1724009fa484" }, { "name": "something2", "id": "50584c03-ac71-4225-9c6a-d12bcc542951" }, { "name": "Unique", "id": "43cf14ee58ea4d8da43e9a2f208d215c" }, { "name": "something4", "id": "ce0374ba-6d9b-4ff5-98b1-1191d1d2a9a7" }, { "name": "something5", "id": "ef825dc3-003c-4740-955a-bb437cfb4199" }],
"arr2": [{ "name": "Unique", "id": "43cf14ee58ea4d8da43e9a2f208d215c" }],
"arr3": [{ "name": "No unique here","id": "Example" }]
}
arr=[]
//loop over dict with pair keys and value
for (const [key, value] of Object.entries(obj)) {
//get the list of name from dict and check it if it contains Unique string
value.map(e=>e.name).includes("Unique") ? arr.push(key) : false
}
console.log(arr)
You can use array some method
const data = {
"arr1": [{
"name": "something1",
"id": "233111f4-9126-490d-a78b-1724009fa484"
},
{
"name": "something2",
"id": "50584c03-ac71-4225-9c6a-d12bcc542951"
},
{
"name": "Unique",
"id": "43cf14ee58ea4d8da43e9a2f208d215c"
},
{
"name": "something4",
"id": "ce0374ba-6d9b-4ff5-98b1-1191d1d2a9a7"
},
{
"name": "something5",
"id": "ef825dc3-003c-4740-955a-bb437cfb4199"
}
],
"arr2": [{
"name": "Unique",
"id": "43cf14ee58ea4d8da43e9a2f208d215c"
}]
}
var obj = [],
keys;
for (keys in data) {
data[keys].some(a => "Unique" === a.name) && obj.push(keys);
}
console.log(obj);
An alternative way that i could think of is using Regexp
var obj = {
"arr1":[
{
"name":"something1",
"id":"233111f4-9126-490d-a78b-1724009fa484"
},
{
"name":"something2",
"id":"50584c03-ac71-4225-9c6a-d12bcc542951"
},
{
"name":"Unique",
"id":"43cf14ee58ea4d8da43e9a2f208d215c"
},
{
"name":"something4",
"id":"ce0374ba-6d9b-4ff5-98b1-1191d1d2a9a7"
},
{
"name":"something5",
"id":"ef825dc3-003c-4740-955a-bb437cfb4199"
}
],
"arr2":
[
{
"name":"Unique",
"id":"43cf14ee58ea4d8da43e9a2f208d215c"}
]
}
let str = JSON.stringify(obj);
let match = str.matchAll(/\"([\w\d]+)\":\[(?:{[\s\S]+},)*{\"name\":\"Unique\"/g);
let parent = [];
for(let m of match){
parent.push(m[1]);
}

javascript filter an object

i have the following Javascript object.
var data =
{
"type": [
"car",
"bike"
],
"wheels": [
"4",
"2"
],
"open": [
"Jan",
"Jan"
],
"wheel_press": [
"35",
"19"
],
"max-weight": [
"4000",
"8"
],
"transition_plan": [
"",
null
],
"number_of_occurence": [
5696,
976
],
"model": [
"sedan",
"street"
}
I want to filter on any of the object key to get only the corresponding values for that key.
so far after searching stackoverflow still not able to find similiar question.
I have tried using
data.filter(type ==='car')
and the error i am getting is
.filter is not a function
the expected output is
if i filter on type === 'car'
then it should only show
{
"type": [
"car"
],
"wheels": [
"4"
],
"open": [
"Jan"
],
"wheel_press": [
"35"
],
"max-weight": [
"4000"
],
"transition_plan": [
""
],
"number_of_occurence": [
5696
],
"model": [
"sedan"
}
You can write a function that finds the index of the value inside the given property and then uses Object.fromEntries(), Object.keys() and Array.map() to create a new object as followings
var data={type:["car","bike"],wheels:["4","2"],open:["Jan","Jan"],wheel_press:["35","19"],"max-weight":["4000","8"],transition_plan:["",null],number_of_occurence:[5696,976],model:["sedan","street"]};
const getFilteredObject = (property, value) => {
const index = data[property].indexOf(value)
return Object.fromEntries(Object.keys(data).map(key => ([key, data[key][index]])))
}
const filteredObject = getFilteredObject('type','car');
console.log(filteredObject)

How to convert array of objects to object with index?

I have a array like this->
var jsonResponse = [
{
"name": "abc",
"value": [
{ "label" : "Daily", "value":"Daily"}
]
},
{
"name": "ccc",
"value": [
{ "label" : "Daily", "value":"Daily"}
]
}
]
And I want to convert it to ->
{
"abc" : {
"name": "abc",
"value": [
{ "label" : "Daily", "value":"Daily"}
]
},
"ccc": {
"name": "ccc",
"value": [
{ "label" : "Daily", "value":"Daily"}
]
}
]
Probably I dont want foreach.
We can do partial with Object.assign( arrayDetails, ...jsonResponse);
But how to do object index?
let indexedResult = {};
jsonResponse.map(obj => indexedResult[obj.name] = obj)
console.log(JSON.stringify(indexedResult));

How to convert string to number in a nested array?

I have the following array of objects which has an array inside an
array. the values are in the string, I want it to be a number. What is
the best possible solution to do that in JavaScript.
[
{
"key": "America",
"values": [
[
"1469664000000",
"1"
],
[
"1469750400000",
"13"
],
[
"1469836800000",
"2"
],
[
"1469923200000",
"1"
],
[
"1470009600000",
"1"
],
[
"1470096000000",
"1"
]
]
},
{
"key": "India",
"values": [
[
"1469750400000",
"1"
]
]
},
{
"key": "China",
"values": [
[
"1469664000000",
"2"
],
[
"1469836800000",
"1"
],
[
"1470096000000",
"12"
]
]
},
{
"key": "Africa",
"values": [
[
"1470096000000",
"1"
]
]
},
{
"key": "UK",
"values": [
[
"1469664000000",
"3"
],
[
"1469750400000",
"3"
],
[
"1469836800000",
"1"
],
[
"1469923200000",
"2"
],
[
"1470009600000",
"4"
],
[
"1470096000000",
"2"
]
]
}
]
var data = [{"key":"America","values":[["1469664000000","1"],["1469750400000","13"],["1469836800000","2"],["1469923200000","1"],["1470009600000","1"],["1470096000000","1"]]},{"key":"India","values":[["1469750400000","1"]]},{"key":"China","values":[["1469664000000","2"],["1469836800000","1"],["1470096000000","12"]]},{"key":"Africa","values":[["1470096000000","1"]]},{"key":"UK","values":[["1469664000000","3"],["1469750400000","3"],["1469836800000","1"],["1469923200000","2"],["1470009600000","4"],["1470096000000","2"]]}];
data.forEach(function (o) {
o.values.forEach(function (values) {
values.forEach(function (value, i) {
values[i] = parseInt(value, 10);
});
});
});
console.log(JSON.stringify(data, null, 4));
var data = [{"key":"America","values":[["1469664000000","1"],["1469750400000","13"],["1469836800000","2"],["1469923200000","1"],["1470009600000","1"],["1470096000000","1"]]},{"key":"India","values":[["1469750400000","1"]]},{"key":"China","values":[["1469664000000","2"],["1469836800000","1"],["1470096000000","12"]]},{"key":"Africa","values":[["1470096000000","1"]]},{"key":"UK","values":[["1469664000000","3"],["1469750400000","3"],["1469836800000","1"],["1469923200000","2"],["1470009600000","4"],["1470096000000","2"]]}];
data = data.map(function(t){
var newVals = t.values.map(function(vs){
return vs.map(function(v){
return parseInt(v, 10);
});
});
return {'key': t.key, values: newVals};
});
console.log(JSON.stringify(data));
You can use JSON.parse(your json object
or maybe use two forEachs

Categories

Resources