convert JSON object to a different one - javascript

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

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.

Grouping elements in array by multiple properties

I have array like this:
var arr = [
{"type":"color","pid":"ITEM_1","id":"ITEM_1_1"},
{"type":"color","pid":"ITEM_2","id":"ITEM_2_2"},
{"type":"size","pid":"DEFAULT_0","id":"DEFAULT_0_1"},
{"type":"size","pid":"DEFAULT_0","id":"DEFAULT_0_2"}
]
And I want to make a new array look like this:
[
{
"type": "color",
"relation":[{"pid": "ITEM_1", "id": "ITEM_1_1"},
{"pid": "ITEM_2", "id": "ITEM_2_2"}]
}, {
"type": "size",
"relation":[{"pid": "DEFAULT_0", "id": ["DEFAULT_0_1","DEFAULT_0_2"]}]
}
]
Thanks.
=========================================
Thanks Abrar's answer. I adjust it slightly for grouping the same pid items and get the result I want. But there should be a better way to do this?
const arr = [
{"type":"color","pid":"ITEM_1","id":"ITEM_1_1"},
{"type":"color","pid":"ITEM_2","id":"ITEM_2_2"},
{"type":"size","pid":"DEFAULT_0","id":"DEFAULT_0_1"},
{"type":"size","pid":"DEFAULT_0","id":"DEFAULT_0_2"}
];
const resultArr = [];
const groups =[];
arr.forEach((data) => {
let type = data.type;
let newArr = arr.filter(el => el.type === type);
let resObj = {
"type": type,
"relation": []
};
newArr.forEach(el => {
groups.push({"pid": el.pid, "id": el.id});
});
var group_to_values = groups.reduce(function(obj, item) {
obj[item.pid] = obj[item.pid] || [];
obj[item.pid].push(item.id);
return obj;
}, {});
resObj.relation.push(group_to_values);
if (resultArr.map(e => e.type).indexOf(type) < 0) {
resultArr.push(resObj);
}
})
console.log(resultArr);
I have refactored your code and now it looks like this -
const arr = [
{"type":"color","pid":"ITEM_1","id":"ITEM_1_1"},
{"type":"color","pid":"ITEM_2","id":"ITEM_2_2"},
{"type":"size","pid":"DEFAULT_0","id":"DEFAULT_0_1"},
{"type":"size","pid":"DEFAULT_0","id":"DEFAULT_0_2"}
];
const resultArr = [];
arr.forEach((data) => {
let type = data.type;
let newArr = arr.filter(el => el.type === type);
let resObj = {
"type": type,
"relation": []
};
newArr.forEach(el => {
resObj.relation.push({"pid": el.pid, "id": el.id});
});
if (resultArr.map(e => e.type).indexOf(type) < 0) {
resultArr.push(resObj);
}
})
console.log(resultArr); //resultArr contains your desired output
Basically I have filtered out the keys from the array based on the type since that has to be unique (as per your desired output). This should be pretty straightforward and won't require frameworks or even jQuery.

Converting an array of 3 arrays into 1 big array with object variable

I'm new to StackOverflow and I know this post might possibly be a duplicate of another so please spare me with all the downvotes and if you think there's an answer to my question out there, please post it and I'll delete this question. Thanks for understanding.
var array1 = ["name", "title", "desc"]
var array2 = [["name1", "name2"], ["title1", "title2"],["desc1", "desc2"]]
How will I turn these into:
[
{name: "name1", title: "title1", desc: "desc1"},
{name: "name2", title: "title2", desc: "desc2"}
]
You can use Array#map, Object.assign (with spread syntax) and the ES6 computed property syntax to achieve that:
const array1 = ["name", "title", "desc"],
array2 = [["name1", "name2"], ["title1", "title2"],["desc1", "desc2"]];
const result = array2[0].map( (_, j) =>
Object.assign(...array1.map( (key, i) => ({ [key]: array2[i][j] }) ))
);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
const result = [];
for(const [index, key] of array1.entries()){
for(const [userindex, value] of array2[index].entries()){
if(!result[userindex])
result[userindex] = {};
result[userindex][key] = value;
}
}
You might go over every key and the values related to the key and assign every key/value pair to the resulting object at the position of the value.
You could reduce the given values array by using the keys as key and the value for new objects.
var keys = ["name", "title", "desc"],
values = [["name1", "name2"], ["title1", "title2"],["desc1", "desc2"]],
objects = values.reduce((r, a, i) => {
a.forEach((v, j) => Object.assign(r[j] = r[j] || {}, { [keys[i]]: v }));
return r;
}, []);
console.log(objects);
You can use this way also:
var array1 = ["name", "title", "desc"];
var array2 = [["name1", "name2"], ["title1", "title2"],["desc1", "desc2"]];
var res = [];
for(var i=0; i<array2[0].length; i++){
var obj = {};
for(var j=0; j<array1.length; j++){
var key = array1[j];
var value = array2[j][i];
obj[key] = value;
}
res.push(obj);
}
console.log(res);

convert nested array to JSON string in js?

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

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

Categories

Resources