Javascript mapping - javascript

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

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

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 Fill array with missing object and value

I have an array like bellow each index contains different set of objects,I want to create an uniformal data where object missing in each index will with Value:0 ,
var d = [
[
{axis:"Email",value:59,id:1},
{axis:"Social Networks",value:56,id:2},
],
[
{axis:"Sending Money",value:18,id:6},
{axis:"Other",value:15,id:7},
]
];
how can I get an array like bellow using above above array
var d = [
[
{axis:"Email",value:59,id:1},
{axis:"Social Networks",value:56,id:2},
{axis:"Sending Money",value:0,id:6},
{axis:"Other",value:0,id:7},
],
[
{axis:"Email",value:0,id:1},
{axis:"Social Networks",value:0,id:2},
{axis:"Sending Money",value:18,id:6},
{axis:"Other",value:15,id:7},
]
];
There are two functions:
getAllEntries that find all objects and stores them into a variable accEntries. Then accEntries is used to search for all occurrences in a sub-array of d. This whole process is done in checkArray.
checkArray is used to fetch all found and not-found entries in d. Both Arrays (found and not-found) are then used to build a new sub-array that contains either found entries with certain values and/or not-found entries with values of 0.
Hope this helps:
var d = [
[
{
axis: 'Email',
value: 59,
id: 1
},
{
axis: 'Social Networks',
value: 56,
id: 2
},
],
[
{
axis: 'Sending Money',
value: 18,
id: 6
},
{
axis: 'Other',
value: 15,
id: 7
},
]
];
function getAllEntries(array) {
var uniqueEntries = [];
array.forEach(function (subarray) {
subarray.forEach(function (obj) {
if (uniqueEntries.indexOf(obj) === - 1) uniqueEntries.push(obj);
});
});
return uniqueEntries;
}
function checkArray(array, acceptedEntries) {
var result = [];
array.forEach(function (subArray) {
var subResult = [];
var foundEntries = [];
subArray.forEach(function (obj) {
if (foundEntries.indexOf(obj.axis) === - 1) foundEntries.push(obj.axis);
});
var notFound = acceptedEntries.filter(function (accepted) {
return foundEntries.indexOf(accepted.axis) === - 1;
});
foundEntries.forEach(function (found) {
subArray.forEach(function (obj) {
if (obj.axis === found) subResult.push(obj);
});
});
notFound.forEach(function (notfound, index) {
subResult.push({
axis: notfound.axis,
value: 0,
id: notfound.id
});
});
result.push(subResult);
});
return result;
}
var accEntries = getAllEntries(d);
var result = checkArray(d, accEntries);
console.log(result);
You can loop over the array to find all the unique objects and then again loop over to push the values that are not present comparing with the array of objects of unique keys.
You can use ES6 syntax to find if an object with an attribute is present like uniKeys.findIndex(obj => obj.axis === val.axis); and the to push with a zero value use the spread syntax like d[index].push({...val, value: 0});
Below is the snippet for the implementation
var d = [
[
{axis:"Email",value:59,id:1},
{axis:"Social Networks",value:56,id:2},
],
[
{axis:"Sending Money",value:18,id:6},
{axis:"Other",value:15,id:7},
{axis:"Social Networks",value:89,id:2},
]
];
var uniKeys = [];
$.each(d, function(index, item) {
$.each(item, function(idx, val){
const pos = uniKeys.findIndex(obj => obj.axis === val.axis);
if(pos == - 1) {
uniKeys.push(val);
}
})
})
$.each(d, function(index, item) {
var temp = [];
$.each(uniKeys, function(idx, val){
const pos = item.findIndex(obj => obj.axis === val.axis);
if(pos == - 1) {
d[index].push({...val, value: 0});
}
})
})
console.log(d);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
How about a short shallowCopy function (Object.assign is not available in IE) and otherwise less than 10 new lines of code?
var d = [
[
{axis:"Email",value:59,id:1},
{axis:"Social Networks",value:56,id:2}
],
[
{axis:"Sending Money",value:18,id:6},
{axis:"Other",value:15,id:7}
]
];
var newD_0 = [shallowCopy(d[0][0]), shallowCopy(d[0][1]), shallowCopy(d[1][0]), shallowCopy(d[1][1])];
var newD_1 = [shallowCopy(d[0][0]), shallowCopy(d[0][1]), shallowCopy(d[1][0]), shallowCopy(d[1][1])];
newD_0[2].id = 0;
newD_0[3].id = 0;
newD_1[0].id = 0;
newD_1[1].id = 0;
d = [newD_0, newD_1];
function shallowCopy(obj) {
var copy = {};
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
copy[key] = obj[key];
}
}
return copy;
}
console.log(JSON.stringify(d));
RESULT:
[
[
{
"axis":"Email",
"value":59,
"id":1
},
{
"axis":"Social Networks",
"value":56,
"id":2
},
{
"axis":"Sending Money",
"value":18,
"id":0
},
{
"axis":"Other",
"value":15,
"id":0
}
],
[
{
"axis":"Email",
"value":59,
"id":0
},
{
"axis":"Social Networks",
"value":56,
"id":0
},
{
"axis":"Sending Money",
"value":18,
"id":6
},
{
"axis":"Other",
"value":15,
"id":7
}
]
]

Categories

Resources