java script to transform json data - javascript

my survey output is like
{"a":"1","b":"2","c":"1","d":"0","e":"please improve","Id":"789"} when it reaches the jsp, and i would like to change 0 to good, 1 to bad and 2 to ok, which are the outputs of a,b,c,d .how can we do it using foreach function.

Something like this?
var input = {"a":"1","b":"2","c":"1","d":"0","e":"please improve","Id":"789"};
var mapvals = {"0":"good", "1":"bad", "2":"ok"};
var newObject = Object.keys(input).reduce(function(previous, current) {
previous[current] = mapvals[input[current]] || input[current];
return previous;
}, {});
console.log(newObject);
Which gives:
{
a: "bad",
b: "ok",
c: "bad",
d: "good",
e: "please improve",
Id: "789"
}
You could do it manually with a forEach function if you really wanted... but I'll leave that to you.

foreach() and map() only work on arrays, so they can't be used directly on your object. You'll have to use the keys() or entries() functions first to get the fields in the object as an array.
Unfortunately Object.entries() currently only works in Firefox(*). However, as it happens, keys() produces simpler code anyway.
var input = {"a":"1","b":"2","c":"1","d":"0","e":"please improve","Id":"789"};
var mapvals = {"0":"good", "1":"bad", "2":"ok"};
var output = {};
Object.keys(input).forEach(function(key) {
output[key] = mapvals[input[key]] || input[key];
});
console.log(output);
(*) It's available in Chrome also, but only behind a configuration flag.

you could convert the values when serializing the object. Before you send the json to the backend:
var data = {"a":"1","b":"2","c":"1","d":"0","e":"please improve","Id":"789"};
var mapvals = {"0":"good", "1":"bad", "2":"ok"};
var json = JSON.stringify(data, (key, value) => key && value in mapvals? mapvals[value]: value);
json:
{"a":"bad","b":"ok","c":"bad","d":"good","e":"please improve","Id":"789"}
you can also add further "filter" to only apply this logic to some keys
also works with more complex data, like the Array of items like that, that you mentioned.
var data = [
{"a":"0","b":"2","c":"0","d":"0","e":" ","id":"456"},
{"a":"0","b":"0","c":"0","d":"0","e":"test","i‌​d":"123"},{"a":"0","‌​b":"2","c":"0","d":"‌​0","e":"please test ","id":"456"},
{"a":"0","b":"2","c":"0","d":"0","e":" ","id":"456"},
{"a":"0","b":"1","c":"1","d":"0","e":" ","id":"456"},
{"a":"2","b":"2","c":"2","d":"2","e":" ","id":"789"},
{"a":"1","b":"1","c":"1","d":"1","e":"survey ","id":"789"},
{"a":"1","b":"1","c":"2","d":"2","e":"1234567"‌​,"id":"789"},
{"a":"0‌​","b":"0","c":"0","d‌​":"0","e":" ","id":"234"}
];
var mapvals = {"0":"good", "1":"bad", "2":"ok"};
var json = JSON.stringify(data, (key, value) => key && value in mapvals? mapvals[value]: value);
json:
[{"a":"good","b":"ok","c":"good","d":"good","e":" ","id":"456"},{"a":"good","b":"good","c":"good","d":"good","e":"test","id":"123"},{"a":"good","b":"ok","c":"good","d":"good","e":"please test ","id":"456"},{"a":"good","b":"ok","c":"good","d":"good","e":" ","id":"456"},{"a":"good","b":"bad","c":"bad","d":"good","e":" ","id":"456"},{"a":"ok","b":"ok","c":"ok","d":"ok","e":" ","id":"789"},{"a":"bad","b":"bad","c":"bad","d":"bad","e":"survey ","id":"789"},{"a":"bad","b":"bad","c":"ok","d":"ok","e":"1234567","id":"789"},{"a":"good","b":"good","c":"good","d":"good","e":" ","id":"234"}]

Related

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);

storing key value pairs in an array in javascript

I have 2 arrays namely,
configdata = ["assignee", "shortDesc"];
ticketarray = ["Tom","testDesc"];
I want to store the values as a key value pair in another array, something like this:
ticketData = ["assignee":"Tom","shortDesc":"testDesc"];
Kindly note that the array values are dynamic, so I cannot hardcode them.
Is there a way to do so? I am able to achieve the above said requirement but the length always shows 0. This is the code that I am using:
configdata.Incident_Field.forEach(function (k, i) {
this[k] = ticketarray[i];
}, ticketData);
Other people have explained why your code did not work. I am providing another solution using reduce.
const configdata = ["assignee", "shortDesc"];
const ticketarray = ["Tom", "testDesc"];
let ticketData = configdata.reduce((result, value, index) => {
result[value] = ticketarray[index];
return result;
}, {});
console.log(ticketData);
Output:
{
assignee: "Tom",
shortDesc: "testDesc"
}
The below is not a valid structure in JavaScript:
ticketData = ["assignee":"Tom","shortDesc":"testDesc"];
What you need is a JavaScript object. The best you can do is:
Make sure both the array lengths are same.
Associate the key and value by creating a new object.
Use Object.keys(obj).length to determine the length.
Start with the following code:
configdata = ["assignee", "shortDesc"];
ticketarray = ["Tom", "testDesc"];
if (configdata.length == ticketarray.length) {
var obj = {};
for (var i = 0; i < configdata.length; i++)
obj[configdata[i]] = ticketarray[i];
}
console.log("Final Object");
console.log(obj);
console.log("Object's Length: " + Object.keys(obj).length);
The above will give you an object of what you liked, a single variable with all the values:
{
"assignee": "Tom",
"shortDesc": "testDesc"
}

Extract only values from JSON object in javascript without using a loop

is there a "Nice" way to get all the values out of a json object (I don't care about the keys) - just get the values into array,
without using a loop ?
(lang is Javascript)
It depends on how you define "loop".
You can extract the properties with Object.keys and then map them to their values.
… it's still essentially a loop under the hood though.
var json = `{ "foo": 1, "bar": 2, "baz": 3 }`;
var obj = JSON.parse(json);
var values = Object.keys(obj).map(function (key) { return obj[key]; });
console.log(values);
With weaker browser support you could use the values method.
var json = `{ "foo": 1, "bar": 2, "baz": 3 }`;
var obj = JSON.parse(json);
var values = Object.values(obj);
console.log(values);
I think you are looking for Object.values() function, just pass the object to the values method of Object as first param. That's it!
Object.values({something: 'lol'});
> ["lol"]
Recursively extract as text
Yes, this is a loop but the underlying methods you are calling such as Object.values or arr.map are still loops. I found this useful for extracting text out of a json object for full text search in particular and thought it useful as I came here initially needing this but the answers only touched the surface as json is recursive in nature.
function textFromJson(json) {
if (json === null || json === undefined) {
return '';
}
if (!Array.isArray(json) && !Object.getPrototypeOf(json).isPrototypeOf(Object)) {
return '' + json;
}
const obj = {};
for (const key of Object.keys(json)) {
obj[key] = textFromJson(json[key]);
}
return Object.values(obj).join(' ');
}
With ES2017 you have Object.values(). You can polyfill it also.
Only you need is transform JSON to JavaScript object and call Object.values(). The result is an array of values.
var obj = JSON.parse(jsonData);
var result = Object.values(obj);
If you pass a function to JSON.parse, it will be called each time a value is parsed:
function get_values(json) {
let values = []
JSON.parse(json, (key,value)=>{ values.push(value) })
return values
}
ex:
get_values(`{"a":1, "b":[true, false], "c":3}`)
// returns a list of:
• 1
• true
• false
• [true, false]
• 3
• {a:1, b:[true, false], c:3}
Note: If you don't consider the full object to be a "value", just remove the last item.

Output value from Json Array

I'm getting output: [{"ref":"contact.html","score":0.7071067811865475}]
$.getJSON( "index.json", function(content) {
idx = lunr.Index.load(content);
var results = idx.search(variabletosearch);
var final = JSON.stringify(results);
console.log(final);
});
How can I print value of ref? When I console.log(final[0].ref); I get undefined.
EDIT:
JSON.stringify returns a string, not an object. So in this case 'final' is a string that contains the same data that was in the object 'results'
To access the data from an object, you can use result[0].ref, or if you want to use 'final' (although you don't need to), you can do this:
final = JSON.parse(final)
console.log(final[0].ref)
If it's only one object within the array, then the other answers are enough, but since arrays are used to store multiple objects, you can do this as follows:
var arr = [
{"ref": "object1", "score": "1"},
{"ref": "object2", "score": "2"}
]
arr.map(function(object) {
console.log(object.ref)
})
JSFiddle using an alert instead of console.log()
You can also use a loop, but this cleaner.
var a = [{"ref":"contact.html","score":0.7071067811865475}];
a[0].ref;
a[0] is the '0'th (or first) element in the array which is the object literal {"ref":"contact.html","score":0.7071067811865475} from here you can access the object normally using dot notation.
Expanded out a bit:
var a = [{"ref":"contact.html","score":0.7071067811865475}];
var myObject = a[0];
console.log(myObject.ref);
//or with null checking
if (myObject) {
console.log(myObject.ref ? myObject.ref : 'no value');
}
Well, assuming
var myvar = [{"ref":"contact.html","score":0.7071067811865475}];
then:
var myref = myvar[0].ref;

Uncaught TypeError: data.push is not a function

I am trying to push
data.push({"country": "IN"});
as new id and value to a json string. but it gives the following error
Uncaught TypeError: data.push is not a function
data{"name":"ananta","age":"15"}
Advance Thanks for your reply
To use the push function of an Array your var needs to be an Array.
Change data{"name":"ananta","age":"15"} to following:
var data = [
{
"name": "ananta",
"age": "15",
"country": "Atlanta"
}
];
data.push({"name": "Tony Montana", "age": "99"});
data.push({"country": "IN"});
..
The containing Array Items will be typeof Object and you can do following:
var text = "You are " + data[0]->age + " old and come from " + data[0]->country;
Notice: Try to be consistent. In my example, one array contained object properties name and age while the other only contains country. If I iterate this with for or forEach then I can't always check for one property, because my example contains Items that changing.
Perfect would be: data.push({ "name": "Max", "age": "5", "country": "Anywhere" } );
So you can iterate and always can get the properties, even if they are empty, null or undefined.
edit
Cool stuff to know:
var array = new Array();
is similar to:
var array = [];
Also:
var object = new Object();
is similar to:
var object = {};
You also can combine them:
var objectArray = [{}, {}, {}];
Your data variable contains an object, not an array, and objects do not have the push function as the error states. To do what you need you can do this:
data.country = 'IN';
Or
data['country'] = 'IN';
Also make sure that the name of the variable is not some kind of a language keyword.
For instance, the following produces the same type of error:
var history = [];
history.push("what a mess");
replacing it for:
var history123 = [];
history123.push("pray for a better language");
works as expected.
you can use push method only if the object is an array:
var data = new Array();
data.push({"country": "IN"}).
OR
data['country'] = "IN"
if it's just an object you can use
data.country = "IN";
I think you set it as
var data = [];
but after some time you made it like:
data = 'some thing which is not an array';
then
data.push('') will not work as it is not an array anymore.
One things to remember push work only with array[] not object{}.
If you want to add object o inside inside n like that :
a = {
b:"c",
D:"e",
F: {
g:"h",
I:"j",
k: {
l:"m"
}
}
}
a.F.k.n = { o: "p" };
console.log(a);
Try This Code $scope.DSRListGrid.data = data; this one for source data
for (var prop in data[0]) {
if (data[0].hasOwnProperty(prop)) {
$scope.ListColumns.push(
{
"name": prop,
"field": prop,
"width": 150,
"headerCellClass": 'font-12'
}
);
}
}
console.log($scope.ListColumns);
make sure you push into an Array only
and if their is error like Uncaught TypeError: data.push is not a function**
then check for type of data
you can do this by consol.log(data)
hope this will help
let dataArray = [{'id':1,'code':'ABC'},{'id':1,'code':'ABC'},{'id':2,'code':'ABC'}]
let obj = {};
dataArray.forEach(task => {
task.id in obj ? obj[task.employee_id].push(task):
obj = {
...obj,
[task.employee_id]: [task],
}
});

Categories

Resources