Json Array object to string logic - javascript

Not sure if I'm repeating the question or concept.
How do I convert the below sample to the below string format (may not be correct JSON format)
[{ "Name":"Test1","check":"true},{ "Name":"Test2","check":"true},{ "Name":"Test3","check":"false"}]
string format with appending - for false
Expected o/p:
"Test1","Test2","-Test3"
I have tried concatenating, but it always ends up with
"Test1,Test2-Test3"
But I am looking for 3 separate string separated by comma. Any hint would help

You can simply iterate through your array and collect the object in your required format:
var obj = [{
"Name" : "Test1",
"check" : true
}, {
"Name" : "Test2",
"check" : true
}, {
"Name" : "Test3",
"check" : false
}
];
var result = obj.map(function(x) {
return x.check ? x.Name : "-" + x.Name;
});
document.body.innerHTML = JSON.stringify(result);
Note that I have changed the format of your JSON in order to make it valid.
Just in case if you actually have a string true and false, and you can't change this, you can simply compare it as a string:
var obj = [{
"Name" : "Test1",
"check" : "true"
}, {
"Name" : "Test2",
"check" : "true"
}, {
"Name" : "Test3",
"check" : "false"
}
];
var result = obj.map(function(x) {
return x.check === 'true' ? x.Name : "-" + x.Name;
});
document.body.innerHTML = JSON.stringify(result);

HTML
<div id="output"></div>
Javascript
var obj = [{
"Name" : "Test1",
"check" : true
}, {
"Name" : "Test2",
"check" : true
}, {
"Name" : "Test3",
"check" : false
}
];
function getNames(){
var length=obj.length;
// alert(length);
var op=[];
for(var i=0;i<obj.length;i++){
// alert(obj[i].Name);
op[i]='"'+obj[i].Name+'"';
}
document.getElementById("output").innerHTML=op;
}
getNames();
Your output is there as expected.

Just loop through the valid JSON array(obj) and append the required values(obj.Name) to the empty string(str) based on the condition(appending '-' for 'false' value of obj.check).
var obj = [{
"Name" : "Test1",
"check" : true
}, {
"Name" : "Test2",
"check" : true
}, {
"Name" : "Test3",
"check" : false
}
];
var str = '';
for(var x in obj){
str += (obj[x].check === true) ? obj[x].Name : '-'+obj[x].Name;
str += (x != (obj.length-1)) ? ',' : '';
}
alert(str);

Related

delete from json conditionally

I have some JSON that looks like this
var js = '{
"person" : {
"firstname" : "Steve",
"lastname" : "Smith",
"other": [
{
"age" : "32",
"deceased" : false
},
{
"age" : "14",
"deceased" : false
},
{
"age" : "421",
"deceased" : false
}
]
}
}'
I know how I delete all of "other" by doing this
var j = JSON.parse(js)
delete j[person.other]
but what I really want is to delete the "other" node with a condition that is age = 14.
The result JSON I am looking for is
{
"person" : {
"firstname" : "Steve",
"lastname" : "Smith",
"other": [
{
"age" : "32",
"deceased" : false
},
{
"age" : "421",
"deceased" : false
}
]
}
}
I have looked at the delete operator here and it does not provide a conditional.
Sorry if this is too simple a question. I am learning.
Thanks
The best approach to this would be not to alter the json, but create another one instead:
const filtered = { ...json, other: json.other.filter(item => item.age !== "14") }
If you really need to alter the json, you can do the following:
let index = json.other.findIndex(item => item.age === "14")
while (index !== -1) {
json.other.splice(index, 1)
index = json.other.findIndex(item => item.age === "14")
}
You can use a filter on the array doing something like
j[person.other].filter(x => x.age != 14)
Doc on how filter works more in depth here :
https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

Duplicate entire array if an object of the array contains multiple comma seperated values in Javascript

I have an nested array with objects docs, which I first flatten to one level.
And I have another flat array called multiValueSelected.
Now I'd like to iterate through all objects of the flattened docs-array and check if the key is also in the multiValueSelected-array.
If so, I would like to copy the entire docs-array for every comma separated value for the specific key, copy all other objects and add the new doc to the table.
With this following approach, I'm able to iterate through all comma separated values, but how can I duplicate the entire docs-array? Thank you for your help.
Example Arrays:
docs [{"id" : "test1", "color" : "green,blue,grey", "size" : "s,m"}, {"id" : "test2", "color" : "green", "size" : "l"}...]
multiValueSelected {"color, size, ..."}
Expected result for data:
1. {"id" : "test1", "color" : "green", "size" : ""}
2. {"id" : "test1", "color" : "blue", "size" : ""}
3. {"id" : "test1", "color" : "grey", "size" : ""}
4. {"id" : "test1", "color" : "", "size" : "s"}
5. {"id" : "test1", "color" : "", "size" : "m"}
6. {"id" : "test2", "color" : "green", "size" : "l"}
Script:
function importTableau(docs, table) {
var data = [];
var importedDocs = 0;
for (var i = 0; i < docs.length; i++) {
var flatten = objectFlattenData(docs[i])
var rec = {}
for (var key in flatten) {
// var key deiines the KEY
// var flatten[key] defines the VALUE without duplicates
// var flatten defines the CURRENT DOCUMENT
if (multiValueSelected.indexOf(key) > -1) {
//console.log('key: ', key, ' flatten: ', flatten[key])
var flattenString = flatten[key];
var id = key.replace(/[^A-Za-z0-9_]+/g, '')
// handling multivalues as seperate doc per value
var properties = flattenString.split(',');
var propertiesLength = properties.length;
for (var i = 0; i < propertiesLength; i++) {
// Trim the excess whitespace.
properties[i] = properties[i].replace(/^\s*/, "").replace(/\s*$/, "");
// Get the single Value
var singleValue = properties[i]
console.log(singleValue);
rec[id] = flatten[singleValue];
data.push(rec);
}
return false;
} else {
// not selected for handling multivalues as seperate doc
var id = key.replace(/[^A-Za-z0-9_]+/g, '')
rec[id] = flatten[key];
};
};
data.push(rec);
};
table.appendRows(data);
It seems a little confusing your expected output, but maybe this is what you want?
let docs = [{
"id": "test1",
"color": "green,blue,grey",
"size": "s,m"
}, {
"id": "test2",
"color": "green",
"size": "l"
}];
let multiValueSelected = ["color", "size"];
let data = [];
for (selected_value of multiValueSelected) {
for (doc of docs) {
if (doc.hasOwnProperty(selected_value)) {
let values = doc[selected_value].split(',');
for (value of values) {
let obj = {id: doc.id};
let keys = Object.keys(doc).filter(k => !['id', selected_value].includes(k));
keys.map(k => obj[k] = '');
obj[selected_value] = value;
data.push(obj);
}
}
}
}
console.log(data)
I really have not understand the question, but if you want to have this:
Input: docs [{"id" : "test1", "color" : "green,blue,grey", "size" : "s,m"}, {"id" : "test2", "color" : "green", "size" : "l"}...]
Output: multiValueSelected ["color, size, ...", "...."]
as an output you can't have [{"color, size, ..."}] because is not a valid json, a json is a composition of key-value pair and not just only a string
You can do this:
const docs = [{"id" : "test1", "color" : "green,blue,grey", "size" : "s,m"}, {"id" : "test2", "color" : "green", "size" : "l"}...];
const multiValueSelected = [];
docs.forEach(doc => {
let currentValue = "";
Object.keys(doc).forEach(key => {
if(doc[key].split(',').length > 1)
currentValue = (currentValue === "") ? key : ", " + key;
}
if(currentValue !== "") multiValueSelected.push(currentValue);
}
if you want as output this [{"color": "green,blue,grey" , "size" : "s,m" }, {"....": "....", ....}]
const docs = [{"id" : "test1", "color" : "green,blue,grey", "size" : "s,m"}, {"id" : "test2", "color" : "green", "size" : "l"}...];
const multiValueSelected = [];
docs.forEach(doc => {
const currentValue = {};
Object.keys(doc).forEach(key => {
if(doc[key].split(',').length > 1)
currentValue[key] = doc[key];
}
if(Object.keys(currentValue).length > 0) multiValueSelected.push(currentValue);
}
please let me know if I have not responded to your question

object.push(array) is not working

I am using for loop to get the units onebyone and inside loop I am getting the array of volumes like below. now I want to push that array to respective unit so I used push but here I am getting error.
My code is below
$scope.UnitDetails = [{
UnitId : "001"
Unit1 : "A"
Fields: [{"one" : "true","Isactive" : true },
{"two" : "false","Isactive" : true }
]
},
{
UnitId : "002"
Unit1 : "B"
Fields: [{"one" : "true","Isactive" : true },
{"two" : "false","Isactive" : true }
]
}]
for(i= 0; i < $scope.UnitDetails.length ; i++){
var volume = [];
volume.Volume_AL = eval($scope.VolumeFormula.AL);
volume.Volume_BL = eval($scope.VolumeFormula.BL);
volume.Volume_CL = eval($scope.VolumeFormula.CL);
volume.Volume_DL = eval($scope.VolumeFormula.DL);
$scope.UnitDetails[i].push(volume);
}
Can anyone find where i am doing mistake
EDIT
When I try as below then it is creating another array in object as below
for(i= 0; i < $scope.UnitDetails.length ; i++){
var volume = {};
volume.Volume_AL = eval($scope.VolumeFormula.AL);
volume.Volume_BL = eval($scope.VolumeFormula.BL);
volume.Volume_CL = eval($scope.VolumeFormula.CL);
volume.Volume_DL = eval($scope.VolumeFormula.DL);
$scope.UnitDetails.push(volume);
}
What I got
$scope.UnitDetails = [{
UnitId : "001"
Unit1 : "A"
Fields: [{"one" : "true","Isactive" : true },
{"two" : "false","Isactive" : true }
]
},
{
UnitId : "002"
Unit1 : "B"
Fields: [{"one" : "true","Isactive" : true },
{"two" : "false","Isactive" : true }
]
},
{
Volume_CL:0,
Volume_EQ:12,
Volume_PH:54,
Volume_RW: 24
}]
My Expected :
$scope.UnitDetails = [{
UnitId : "001"
Unit1 : "A"
Fields: [{"one" : "true","Isactive" : true },
{"two" : "false","Isactive" : true }
]
volume : [ {
Volume_CL:0,
Volume_EQ:12,
Volume_PH:54,
Volume_RW: 24
}]
},
{
UnitId : "002"
Unit1 : "B"
Fields: [{"one" : "true","Isactive" : true },
{"two" : "false","Isactive" : true }
]
volume : [ {
Volume_CL:0,
Volume_EQ:12,
Volume_PH:54,
Volume_RW: 24
}]
},
]
To achieve the desired result you could append the volume array dynamically to each element of $scope.UnitDetails:
for (var i = 0; i < $scope.UnitDetails.length; i++) {
$scope.UnitDetails[i].volume = [{
Volume_AL: eval($scope.VolumeFormula.AL),
Volume_BL: eval($scope.VolumeFormula.BL),
Volume_CL: eval($scope.VolumeFormula.CL),
Volume_DL: eval($scope.VolumeFormula.DL)
}];
}
Remark: The eval statement allows for execution of arbitrary javascript code and if the input is coming from your users you might want to ensure that it doesn't contain any malicious code before passing it to this function. Or even better do not use eval at all. Depending on your requirements you might find a more appropriate and restrictive function to achieve your goal. For example if you are expecting to evaluate only mathematical expressions written from your clients you might find a library designed exactly for this purpose rather than using the general purpose eval statement.

JSON: key value concatenation in javascript

I'm trying to parse json object to get the key and value concatenated to a variable.
My desired output from the given json is:
"/" - 7.84 GiB; "/opt" - 4.86 GiB; "/usr" - 4.80 GiB
Using my snippet i can get objects but struggling to get the name and value in desired format. Please assist.
for (i = 0; i < obj.length; i++)
{
if ( obj[i].name === 'mountpoints')
{
js_mountpoints = obj[i].value;
break;
}
js_mountpoints = 'NA';
}
My JSON input:
[{
"name" : "pe_build",
"value" : "2016.2.1"
},
{
"name" : "kernel",
"value" : "Linux"
}, {
"name" : "blockdevices",
"value" : "sda,sdb,sr0"
},
{
"name" : "mountpoints",
"value" : {
"\/boot\/efi" : {
"size_bytes" : 261861376,
"size" : "249.73 MiB",
"capacity" : "0%"
},
"\/opt" : {
"size_bytes" : 2086666240,
"size" : "1.94 GiB",
"capacity" : "1.64%"
},
"\/boot" : {
"size_bytes" : 258650112,
"size" : "246.67 MiB",
"capacity" : "74.28%"
},
"\/var" : {
"size_bytes" : 10475274240,
"size" : "9.76 GiB",
"filesystem" : "xfs",
"capacity" : "4.01%"
}
}
}, {
"name" : "uptime_seconds",
"value" : 244181
}, {
"name" : "memoryfree",
"value" : "6.66 GiB"
}, {
"name" : "memoryfree_mb",
"value" : 6816.91796875
}
]
finalStr = ''
Object.keys(obj).forEach(function(key) {
if (obj[key].name === 'mountpoints') { // only get sizes for mountpoints
var value = obj[key].value;
Object.keys(value).forEach(function(name) { // add all sizes to string
finalStr += '"' + name + '" - ' + value[name].size + ';';
}); //update
}
}); //update
if (finalStr.length > 0) { // at least one entry was added
finalStr.slice(0, -1);
}

Dynamic Mapping using jquery.map()

I have a series of ajax json responses that I need to convert to a common type of array. The issue is that each json response is slightly different.
Here are two examples of responses I might receive:
var contacts = [{ "ContactId" : "1", "ContactName" : "Bob" },{ "ContactId" : "2", "ContactName" : "Ted" }];
var sites = [{ "SiteId" : "1", "Location" : "MN" },{ "SiteId" : "2", "Location" : "FL" }];
I'm trying to write a method that converts either collection to a common type. An example of the above responses converted would look like this:
var convertedContacts = [{ "value" : "1", "text" : "Bob" },{ "value" : "2", "text" : "Ted" }];
var convertedSites = [{ "value" : "1", "text" : "MN" },{ "value" : "2", "text" : "FL" }];
So I'm trying to use the map function of jquery to facilitate this requirement. Although I can't seem to figure out how to dynamically query for the different property values that will exist depending on which json collection I'm passing into the function.
Here is an example of what I'm trying to do:
function ConvertResponse(arrayToConvert, text, value)
{
var a = $.map(arrayToConvert, function(m) {
return "{ \"text\" : "+eval("m."+text)+", \"value\" : "+eval("m."+value)+" }"
});
}
I also tried this:
function ConvertResponse(arrayToConvert, text, value)
{
var a = $.map(arrayToConvert, function(m) {
return "{ \"text\" : " + m.$(text) + ", \"value\" : " + m.$(value) + " }";
});
}
And this is how you would call it:
var convertedContacts = ConvertResponse(contacts, "ContactName", "ContactId");
var convertedSites = ConvertResponse(contacts, "Location", "SiteId");
Unfortunately this does not seem to work in the least.
Like this?
var contacts = [{ "ContactId" : "1", "ContactName" : "Bob" },{ "ContactId" : "2", "ContactName" : "Ted" }];
var sites = [{ "SiteId" : "1", "Location" : "MN" },{ "SiteId" : "2", "Location" : "FL" }];
function convertResponse(response, text, value) {
return $.map(response, function(it) {
return {
value: it[value],
text: it[text]
};
});
}
var convertedContacts = convertResponse(contacts, 'ContactId', 'ContactName');
var convertedSites = convertResponse(sites, 'SiteId', 'Location');

Categories

Resources