convert nested array to JSON string in js? - javascript

I have a set of array like this : [["Sarah"],["Jamie"],["B"],["148"]]
and I want to convert this into JSON string with specific element for each vaues. For example,
{ "name":"Sarah", "grade":"148", "School":"B"...}
How should I proceed? I tried to toString the array then bind with this element but it doesn't work out well..
Original Json
"Data":{
"Table":[
{
"Name":[
"Jamie"
],
"School":[
"A"
],
"grade":[
"99"
]
},
{
"Name":[
"Mike"
],
"School":[
"B"
],
"grade":[
"148"
]
}
]
}
}

You can try with the simple forEach
var data = {"Data": {"Table": [{"Name": ["Jamie"],"School": ["A"],"grade": ["99"]},{"Name": ["Mike"],"School": ["B"],"grade": ["148"]}]}};
var items = [];
data['Data']['Table'].forEach(function(item){
items.push({name: item.Name[0], grade: item.grade[0], school: item.School[0]});
});
console.log(JSON.stringify(items));

You can use reduce to do this!
let newData = data.Data.Table.reduce(function(arr, obj) {
let newObj = {};
for (let key in obj) {
newObj[key] = obj[key][0]
}
arr.push(newObj);
return arr;
}, [])
Demo: https://jsfiddle.net/500eo2gp/

let newDataArray = this.data.Data.Table.reduce(function(arr, obj) {
let newObj = {};
for (let key in obj) {
newObj[key] = obj[key][0]
}
arr.push(newObj);
return arr;
}, []
);
newData =JSON.stringify(newDataArray);
JSON.stringify(newDataArray) array from tymeJV 's code snippet will give you the JSON string as follows.
[{"Name":"Jamie","School":"A","grade":"99"},{"Name":"Mike","School":"B","grade":"148"}]
Demo:
http://plnkr.co/edit/wPhVTOFhRgERLXKCuoYl?p=preview

Related

How to add properties for all the keys and values in an object?

I have a Javascript Object :
{
"Central":73322346.47533998,
"East":87801368.39711998,
"North":76468694.37534,
"South":142687496.66816995,
"West":76815749.40554999
}
I want to map this object into an array that look like this
[
{"name" :"Central ,"size" : 73322346.47533998},
{"name" : "East", "size" : 87801368.39711998},
{"name": "North","size":76468694.37534},
{"name": "South","size" :142687496.66816995},
{"name":"West","size":76815749.40554999}
]
How do I go about?
do like this:
obj = {"Central":73322346.47533998,"East":87801368.39711998,"North":76468694.37534,"South":142687496.66816995,"West":76815749.40554999}
out = [];
Object.keys(obj).forEach(function(d){ out.push({name: d, size: obj[d]});})
//out will contain your formatted data
In ES2017 you can do:
Object.entries(obj).map(([name, size])=> ({name, size}))
var obj = {
"Central":73322346.47533998,
"East":87801368.39711998,
"North":76468694.37534,
"South":142687496.66816995,
"West":76815749.40554999
}
var res = Object.entries(obj).map(([name, size])=> ({name, size}));
console.log(res);
In ES2011 (5.1), ES2015 (6),.... and onward you can do:
Object.keys(obj).map(function(k) {
return {name: k, size: obj[k]}
})
var obj = {
"Central":73322346.47533998,
"East":87801368.39711998,
"North":76468694.37534,
"South":142687496.66816995,
"West":76815749.40554999
}
var res = Object.keys(obj).map(function(k) {
return {name: k, size: obj[k]}
})
console.log(res)
You can loop over the keys of the object to get the array of objects as expected:
var data = {"Central":73322346.47533998,"East":87801368.39711998,"North":76468694.37534,"South":142687496.66816995,"West":76815749.40554999};
var res = [];
Object.keys(data).forEach((key)=>{
res.push({
name: key,
size: data[key]
});
});
console.log(res);
A simple way to do this is to interate over the keys of the input object using a for..in loop:
const input = {
"Central": 73322346.47533998,
"East": 87801368.39711998,
"North": 76468694.37534,
"South": 142687496.66816995,
"West": 76815749.40554999
};
let output = [];
for (const key in input)
{
output.push({ "name": key, "size": input[key] });
}
console.log(output);
This is probably the fastest way to achieve the desired output.

Lodash merge array with dictionary object key values

I have an array
var keys = ['Name','Id'];
which I want to merge with the dictionary object below
var projects = {
"project1": "11111",
"project2": "22222",
"project3": "33333",
};
to produce the output below
output =
[
{ Name:"project1", Id:"11111"},
{ Name:"project2", Id:"22222"},
{ Name:"project3", Id:"33333"},
]
I have tried using
console.log(_.zipObject(keys, projects));
but this fails woefully
How do I do this using lodash?
Since you have asked to use lodash specifically, you can use _.map.
DEMO
var projects = {
"project1": "11111",
"project2": "22222",
"project3": "33333",
};
var result = _.map(projects, function(value, prop) {
return { Name: prop, id: value };
});
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.2/lodash.min.js"></script>
Use Object.keys() with Array.map() to create the array of objects. You can assign the key names by using computed property names:
var keys = ['Name','Id'];
var projects = {
"project1": "11111",
"project2": "22222",
"project3": "33333",
};
var result = Object.keys(projects)
.map(function(k) {
return {
[keys[0]]: k,
[keys[1]]: projects[k]
};
});
console.log(result);

convert JSON object to a different one

i have this json:
[
{
"AF28110": 33456.75,
"AF27989": 13297.26
}
]
and i want to convert it to:
[
{ "name": "AF28110", "price": 33456.75},
{ "name": "AF27989", "price": 13297.26}
]
I have tried various making it with .map() but i cannot make it work.
does anyone have any idea how to do this?
thank you
You can try following code:
let output = [];
input.forEach(obj => Object.getOwnPropertyNames(obj).forEach(key => output.push({name: key, price: obj[key]})))
Object.getOwnPropertyNames will give you names of your properties and then you can transform each name to a separate output array item.
Using map:
const data = [
{
"AF28110": 33456.75,
"AF27989": 13297.26
}
]
const out = Object.keys(data[0]).map(el => {
return { name: el, price: data[0][el] };
});
console.log(out)
Here's a way using concat, Object.keys, and map. You can take each item from the array, get the keys from that object, and then map each key to the name/price object you want. Do that for each item, then flatten the result (using concat).
Example:
const arr = [{
"AF28110": 33456.75,
"AF27989": 13297.26
}]
const result = [].concat(...arr.map(o => Object.keys(o).map(k => ({name: k, price: o[k]}))))
console.log(result);
If you have multiple objects on the array, you can use reduce
let arr = [
{"AF28110": 33456.75,"AF27989": 13297.26},
{"AF28111": 33456.20,"AF27984": 13297.88}
];
let result = arr.reduce((c, v) => c.concat(Object.entries(v).map(o => {return {name: o[0],price: o[1]}})), []);
console.log(result);
Try this,
var text = '[{"AF28110": 33456.75,"AF27989": 13297.26}]';
var obj = JSON.parse(text);
var result = [];
for (i = 0; i < obj.length; i++) {
var keys = Object.keys(obj[i]);
for (j = 0; j < keys.length; j++){
result[j] = '{ "name":' +keys[j] + ', "price":' + obj[i][keys[j]]+'}';
}
}
console.log(result);
Thanks.
Ways to achieve :
Using Object.keys method :
var jsonObj = [
{
"AF28110": 33456.75,
"AF27989": 13297.26
}
];
var res = Object.keys(jsonObj[0]).map(item => {
return {"name": item, "price": jsonObj[0][item] };
});
console.log(res);
Using Object.getOwnPropertyNames method :
var jsonObj = [
{
"AF28110": 33456.75,
"AF27989": 13297.26
}
];
var res = Object.getOwnPropertyNames(jsonObj[0]).map(item => {
return {"name": item, "price": jsonObj[0][item] };
});
console.log(res);

Javascript mapping

In our project we are getting below data from DB in following format.
[
[
"ClearDB",
"test1#test.com",
"com.test.cleardb"
],
[
"Cricbuzz",
"test2#test.com",
"com.test.cricbuzz"
],
[
"Hangout",
"test3#test.com",
"com.test.hangout"
]
]
I want this in key value format as mentioned below
[
{
"projname": "ClearDB",
"projmanager": "test1#test.com",
"package": "com.test.cleardb"
},
{
"projname": "Cricbuzz",
"projmanager": "test2#test.com",
"package": "com.test.cricbuzz"
},
{
"projname": "Hangout",
"projmanager": "test3#test.com",
"package": "com.test.hangout"
}
]
Please provide me a proper way to implement this.
You can simply create a new object for each of the arrays, and create an array of objects with map function, like this
var keys = ["projname", "projmanager", "package"];
console.log(data.map(function (arr) {
var obj = {};
keys.forEach(function (key, idx) { obj[key] = arr[idx]; });
return obj;
}));
Output
[ { projname: 'ClearDB',
projmanager: 'test1#test.com',
package: 'com.test.cleardb' },
{ projname: 'Cricbuzz',
projmanager: 'test2#test.com',
package: 'com.test.cricbuzz' },
{ projname: 'Hangout',
projmanager: 'test3#test.com',
package: 'com.test.hangout' } ]
with Array.prototype.map:
var results = db.map(function (v) {
return {
projname: v[0],
projmanager: v[1],
package: v[2]
};
});
Suppose the data you are getting from database is stored in variable 'abc'
var abc = [];
var output = [];
for(var i = 0; i< abc.length; i++){
output[i] = {};
output[i].projname = abc[i][0];
output[i].projmanager = abc[i][1];
output[i].package = abc[i][2];
}
Note: 'abc' is the variable where you are storing data from DB.
In ES6:
input . map(([projname, projmanager, package]) => ({projname, projmanager, package}));
The part in [] deconstructs the parameter to map, which is one of the subarrays, assigning the first element to projname, and so on. The part in {} creates and returns an object with a key of 'projname' whose value is projname, etc.
If you want to generalize this to use any array of field names (['projname', 'projmanager', 'package']):
input . map(
values =>
values . reduce(
(result, value, i) => {
result[fieldnames[i]] = value;
return result;
},
{}
)
);
if
var array =[
[
"ClearDB",
"test1#test.com",
"com.test.cleardb"
],
[
"Cricbuzz",
"test2#test.com",
"com.test.cricbuzz"
],
[
"Hangout",
"test3#test.com",
"com.test.hangout"
]
];
then
var obj = [];
array.each(function(item){ obj.push({"projname": item[0],
"projmanager":item[1],
"package": item[2]})
});
Edit:
Using Jquery
var obj = [];
$.each(array,function(key,value){ obj.push({"projname": value[0],
"projmanager":value[1],
"package": value[2]})
});
Using javascript
var obj = [];
array.forEach(function(item){ obj.push({"projname": item[0],
"projmanager":item[1],
"package": item[2]})
});

Convert one javascript nested object data structure to nested arrays

I am trying to convert a JSON string in a Javascript object literal. I think it is possible with some loops, but i couldn't get it done. The target structure is shown below, "chartData".
Fiddle can be found here: http://jsbin.com/ajemih/13/edit
Here's the JSON data:
{
"1b":{
"allLoad":"130",
"loadMovement":"111",
"allMovement":"111"
},
"1a":{
"allLoad":"910",
"loadMovement":"671",
"allMovement":"280"
},
"systemLoad":"963"
}
This should it look like after the conversion:
chartData = [[['loadMovement', 111],
['allMovement', 120],
['allLoad', 130]],
[['Load+Move', 671],
['allMovement', 280],
['allLoad', 910]]];
I think this would work:
Working demo: http://jsfiddle.net/jfriend00/YmjDR/
var data = {
"1b":{
"allLoad":"130",
"loadMovement":"111",
"allMovement":"111"
},
"1a":{
"allLoad":"910",
"loadMovement":"671",
"allMovement":"280"
},
"systemLoad":"963"
};
var chartData = [];
for (var i in data) {
var item = data[i];
var outer = [];
// skip over items in the outer object that aren't nested objects themselves
if (typeof item === "object") {
for (var j in item) {
var temp = [];
temp.push(j);
temp.push(item[j]);
outer.push(temp);
}
}
if (outer.length) {
chartData.push(outer);
}
}
You could do something like this:
var chartData = []
for(var key in data) {
var properties = data[key];
if(typeof properties === "object") {
var array = [];
for(var propKey in properties) {
array.push([propKey, properties[propKey]])
}
chartData.push(array);
}
}
Check out the fiddle.
You need to map the data manually. Thats actually more a diligent but routine piece of work.
var jsonData = 'your json string';
Object.keys( jsonData ).map(function( key ) {
if( typeof jsonData[ key ] === 'object' ) {
return Object.keys( jsonData[ key ] ).sort(function( a, b ) {
return +jsonData[ key ][ a ] - +jsonData[ key ][ b ];
}).map(function( name ) {
return [ name, jsonData[ key ][ name ] ];
});
}
}).filter( Boolean );
The above code will sort each group by its numeric value and then map a new array in the required style. Since .map() possibly returns undefined values on non-object elements, we need to filter those out before or afterwards.
See http://jsfiddle.net/WjZB2/2/
I had similar problem.
My goal was to convert a list of strings into a valid format for http://ivantage.github.io/angular-ivh-treeview/
This was my starting point:
[
"A\\A1\\Test1",
"A\\A1\\Test2",
"A\\A2\\Test3",
"B\\Test4",
"B\\Test5",
"B\\B1\\Test6",
"B\\B1\\Test7",
"B\\B1\\Test8",
"C\\C1\\C1a\\Test9",
"C\\C1\\C1b\\Test10",
"C\\C2\\C2a\\Test11",
"C\\C2\\C2a\\Test12",
"C\\C2\\C2a\\Test13",
"C\\C3\\Test14",
"C\\Test15",
"C\\Test16"
]
And I needed following format:
[
{
"label": "Selected Tests",
"children": [
{
"label": "A",
"children": [
{
"label": "A1",
"children": [
{
"label": "Test1",
"value": true
},
{
"label": "Test2",
"value": true
}
]
},
{
"label": "A2",
"children": [
{
"label": "Test3",
"value": true
}
]
}
]
}
]
}
]
See my solution https://jsfiddle.net/ydt3gewn/

Categories

Resources