I have an array in my database that is being stored in the following format
["size:medium","height:10cm"]
this is problematic to display in a table.
Is there any way that I can convert this into a Javascript object or a JSON string like this?
{"size":"medium","height":"10cm"
}
p.s:i know json.stringfy,json_encode.the thing is they have stored key value pair as one string
You can build an object with the elements of the array and the left part as key and the right part as value of the by : separated strings.
array object
--------------------------- ---------------------------
[ -> {
"size:medium", -> size: "medium",
"height:10cm" -> height: "10cm"
] -> }
var array = ["size:medium", "height:10cm"],
object = array.reduce(function (r, a) {
var t = a.split(':');
r[t[0]] = t[1];
return r;
}, {});
document.write('<pre>' + JSON.stringify(object, 0, 4) + '</pre>');
You can try something like this:
Note: Following code will make array of objects. I don't think {["size:medium", "height:10cm"]} is a valid object
(function() {
var styleArr = ["size:medium", "height:10cm", "font-size: 18px"];
var resultObject = {};
styleArr.forEach(function(item) {
var values = item.replace(/\"/g, '').split(':');
resultObject[values[0]] = values[1];
});
console.log(resultObject)
})()
In Javascript you can use JSON.parse(), in order to convert your array in Javascript Object.
In PHP Use : json_encode(text)
In JavaScript : JSON.parse(text)
Related
I am calling a third party web api, which returns data like this:
{"name":"Marine Lines","name":"jerry"}
I would like to convert this to a Json array, I could do a split by comma first and then by ":". but wondering if there are some better ways?
If the Web API return an object, then you can directly use dot-notation to access the value.
var x = {"name":"Marine Lines","name":"jerry"};
var name = x.name;
console.log(name);
Else if it is a string then you can parse it first using JSON.parse() and then do the same thing.
var x = '{"name":"Marine Lines","name":"jerry"}';
x = JSON.parse(x);
var name = x.name;
console.log(name);
First of all, your object has the name key twice, which means only the latter will be saved. As regards saving your object's values in an array, the following will do:
var
object = {"a": "Marine Lines", "b": "jerry"},
array = [];
/* Iterate over every enumerable property of the object. */
for (var key in object) {
/* Insert the value in the array. */
array[array.length] = object[key];
}
/* Log the created array. */
console.log(array);
This is the first time I am working with javascript. I have the following string:
document.write(str)
[{"company":1,"number_employees":5},
{"company":4,"number_employees":25},
{"company":5,"number_employees":5},
{"company":2,"number_employees":5},
{"company":4,"number_employees":25}]
I need to convert this string such that I summarize them according to the number_employees as follows:
Three companies have number_employees=5 and two companies have number_employees=25
I am currently struggling to convert the string into javascript object. Once I have the asscoiative array, I can convert it into map and count the number_employees.
s_obj = eval('({' + messageBody + '})');
var result = s_obj.reduce(function(map, obj) {
map[obj.key] = obj.val;
return map;
}, {});
This is giving me the following error:
VM181:1 Uncaught SyntaxError: Unexpected token ,
at onMessage ((index):41)
at WebSocket.<anonymous> (stomp.min.js:8)
Any help/hint/guidance would be much appreciated!
Making a couple of assumptions about your data, you might try something like this:
First, convert the JSON string into an Object using the JSON Object, then as you were attempting use Array.prototype.reduce to summarize - (you have the arguments reversed)
var summary = {};
var messageBody = '[{"company":1,"number_employees":5},{"company":4,"number_employees":25},{"company":5,"number_employees":5},{"company":2,"number_employees":5},{"company":4,"number_employees":25}]';
JSON.parse(messageBody).reduce( (acc, cur) => {
acc[cur.number_employees] = (acc[cur.number_employees] || 0) + 1;
return acc;
}, summary);
for(entry of Object.keys(summary)) {
if (summary.hasOwnProperty(entry)) {
console.log(`There are ${summary[entry]} companies with ${entry} employees`);
}
}
I have a string:
[{"data1":"A"},{"data2":"B"},{"data3":"C"}]
I used jQuery to convert this string to json:
test_json = $.parseJSON('[{"data1":"A"},{"data2":"B"},{"data3":"C"}]');
I got 3 objects:
I don't know, how could i get the key and value in this string-json?
Or the format of string-json is wrong?
have you tried cycle thorough the parsed array?
var test_json = $.parseJSON('[{"data1":"A"},{"data2":"B"},{"data3":"C"}]');
for(var a=0;a<test_json.length;a++) {
var obj = test_json[a];
for(var idx in obj) {
console.log(idx, obj[idx]);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
It has parsed the JSON correctly and returned an array of objects. You could do the following to access the first item containing { data1: "A" }:
console.log(tessst[0])
I am trying to convert my uri to object value, as a success level i converted and splited in to array values with colon. But i am not able to onvert those to regular object. any one suggest me a good way. I am suing underscorejs with me.
here is my code :
var ar = ["id:1231", "currency:GBP"];
var outPut = _.map(ar, function(item){
return '{' + item + '}';
})
console.log(outPut); //consoles as ["{id:1231}", "{currency:GBP}"]
how can i get result like this:
var object = {id:1231, currency:GBP}
is underscore has any in build method for this?
There are several ways you could go about this, and Underscore offers helpers for them.
One way would be to use _.reduce to incrementally add key/value pairs to an initially empty "result" object:
var obj = _.reduce(ar, function(result, item) {
var keyAndValue = item.split(":");
result[keyAndValue[0]] = keyAndValue[1];
return result;
}, {});
Note that you can do the same without Underscore unless you have to support IE 8 or earlier.
Without any third part library:
var output = {} ;
var ar = ["id:1231", "currency:GBP"];
ar.forEach(function (item) {
var values = item.split(':') ;
output[values[0]] = values[1] ;
}) ;
Output console.log(output):
Object {id: "1231", currency: "GBP"}
Here is another version using jQuery:
var newObj = {};
$.each( ar, function( i, v ) {
var kv = v.split( ":" );
newObj[ kv[0] ] = kv[ 1 ];
});
// newObj = {id:"1231", currency:"GBP"}
I have a set of data in the format:
[{"title":movietitle1, "id":445, "release":"16JUN1985"}, {"title":movietitle2, "id":487, "release":"12AUG1993"}]
Which I need to convert into JSON formatted as such:
{
"movietitle1":{"id":445,"release":"16JUN1985"},
"movietitle2":{"id":487, "release":"12AUG1993"}
}
I don't have any idea of how to make this happen.
You can do this with JSON.stringify() and some basic data manipulation.
Store your data in a variable, lets call it input_data.
Loop through your data and use each entry to build up another variable, lets call it output_data.
// create an object to store the newly formatted data
var output_data = {};
// the code in here is run once for each item in input_data
for (var i = 0; i < input_data.length; i++) {
// get the current item's title
var title = input_data[i].title;
// use the title as the key in the output data
// and assign the other values to that key
output_data[title] = {
id: input_data[i].id,
release: input_data[i].release
};
}
// use JSON.stringify() to make a valid JSON string
var json = JSON.stringify(output_data);
// now use the variable json which contains your JSON string
What you are asking for is to turn an array into a map , keying by a specific property, If you really want JSON, you can just call JSON.stringify on the resulting JS object.
http://jsfiddle.net/FfE8f/1/
/**
* Given an array and a property name to key by, returns a map that is keyed by each array element's chosen property
* This method supports nested lists
* Sample input: list = [{a: 1, b:2}, {a:5, b:7}, [{a:8, b:6}, {a:7, b:7}]]; prop = 'a'
* Sample output: {'1': {a: 1, b:2}, '5': {a:5, b:7}, '8': {a:8, b:6}, '7':{a:7, b:7}}
* #param {object[]} list of objects to be transformed into a keyed object
* #param {string} keyByProp The name of the property to key by
* #return {object} Map keyed by the given property's values
*/
function mapFromArray (list , keyByProp) {
var map = {};
for (var i=0, item; item = list[i]; i++) {
if (item instanceof Array) {
// Ext.apply just copies all properties from one object to another,
// you'll have to use something else. this is only required to support nested arrays.
Ext.apply(map, mapFromArray(item, keyByProp));
} else {
map[item[keyByProp]] = item;
}
}
return map;
};
console.log(mapFromArray([
{"title": "title 1", "id":445, "release":"16JUN1985"},
{"title":"movietitle2", "id":487, "release":"12AUG1993"}],
"title"
)));
// outputs
{
"title 1": {"title":"title 1","id":445,"release":"16JUN1985"},
"movietitle2": {"title":"movietitle2","id":487,"release":"12AUG1993"}
}
See More efficient way to search an array of javascript objects?
Your mixing terms. I'm assuming you're asking about manipulating data with JavaScript objects and not strings with JSON data. (The later can be converted with JSON.parse).
First iterate over the array and assigning to an object. This kind of data manipulation works well using Underscore, check it out.
In vanilla JS lets try something like this:
var newData = {};
data.forEach(function(item) {
var title = item.title;
delete item.title;
newData[title] = item;
});
A little crufty but gets the job done.
Personally I'd use this Underscore version:
var newData = _(data).chain()
.map(function(item) {
return [item.title, _(item).omit('title')];
})
.object()
.value();