lodash - object transformation - javascript

Data Source
var data = {
"2017-08-09": [
{
"time": "09:00",
"available": true
},
{
"time": "13:00",
"available": true
},
{
"time": "13:30",
"available": true
},
]
}
Desired Transformation
newData = [ "2017-08-09": ['09:00','13:00','13:30'] ]
I have tried the following:
function recursiveFunction(collection){
var newData = [];
_.forOwn(collection, function(value, key){
newData.push( {key});
value.map( item => {
if (item.available === true) newData.key = item.time
})
});
console.log(newData)
};
But not quite there :/
http://jsfiddle.net/oa6nbgpy/

Map across the values using mapValues, filter only the available times and pluck the time using map:
var newData = _.mapValues(data, times => _.map(_.filter(times, 'available'), 'time'));

With vanilla JS, use Object#keys to get an array of keys, and convert them to objects using Array#map, Array#filter and computed property names:
var data = {"2017-08-09":[{"time":"09:00","available":true},{"time":"09:30","available":false},{"time":"11:30","available":true}],"2017-08-10":[{"time":"10:00","available":true},{"time":"10:30","available":false}]};
var result = Object.keys(data).map(function(key) {
return {
[key]: data[key]
.filter(function(o) {
return o.available;
})
.map(function(o) {
return o.time;
})
};
});
console.log(result);

Related

Loop through nested array to return values of object

I have a nested array and what I was trying to do was get all the values of the object embedded inside the array. I am currently getting each embedded object and calling Object.values to get the values but this method isn't efficient when the array size is big. Is there a way to loop through the array and return the values of each object? Any help is appreciated. Thanks in advance.
const data = [{"path":"uploads\\20211115000755-package.json"},{"path":"uploads\\20211115012255-index.html"},{"path":"uploads\\20211115014342-dataServerMid.js"},{"path":"uploads\\20211115031212-index.js"},{"path":"uploads\\20211115031218-uploadDataServer.js"},{"path":"uploads\\20211115031232-index.js"},{"path":"uploads\\20211115031244-dataServerMid.js"},{"path":"uploads\\20211115031250-uploadData.css"},{"path":"uploads\\20211115031303-20211115012255-index.html"},{"path":"uploads\\20211115031318-20211115031303-20211115012255-index.html"},{"path":"uploads\\20211115050204-exportsCapture.JPG"},{"path":"uploads\\20211115052347-[FREE] Stunna 4 Vegas x DaBaby x NLE Choppa Type Beat Call of Duty (320 kbps).mp3"},{"path":"uploads\\20211115200304-Readme.docx"},{"path":"uploads\\20211115202751-Visual Artist Series Fall 2019Corrected.docx"},{"path":"uploads\\20211115203354-ln command examples.docx"},{"path":"uploads\\20211115210027-Q2.docx"},{"path":"uploads\\20211116011817-Fall 2019 ABCD Plattsburgh Syllabi Course Description.docx"}]
//change this to loop and return all the values instead of having to call by index
const dataValues = [Object.values(data[0]).toString(), Object.values(data[1]).toString(), Object.values(data[2]).toString()]
console.log(dataValues)
UPDATE: I tried #yousaf's method. It worked for my 3 item array but not for this:
const data = [{
"path": "uploads\\20211115000755-package.json"
}, {
"path": "uploads\\20211115012255-index.html"
}, {
"path": "uploads\\20211115014342-dataServerMid.js"
}, {
"path": "uploads\\20211115031212-index.js"
}, {
"path": "uploads\\20211115031218-uploadDataServer.js"
}, {
"path": "uploads\\20211115031232-index.js"
}, {
"path": "uploads\\20211115031244-dataServerMid.js"
}, {
"path": "uploads\\20211115031250-uploadData.css"
}, {
"path": "uploads\\20211115031303-20211115012255-index.html"
}, {
"path": "uploads\\20211115031318-20211115031303-20211115012255-index.html"
}, {
"path": "uploads\\20211115050204-exportsCapture.JPG"
}, {
"path": "uploads\\20211115052347-[FREE] Stunna 4 Vegas x DaBaby x NLE Choppa Type Beat Call of Duty (320 kbps).mp3"
}, {
"path": "uploads\\20211115200304-Readme.docx"
}, {
"path": "uploads\\20211115202751-Visual Artist Series Fall 2019Corrected.docx"
}, {
"path": "uploads\\20211115203354-ln command examples.docx"
}, {
"path": "uploads\\20211115210027-Q2.docx"
}, {
"path": "uploads\\20211116011817-Fall 2019.docx"
}]
//change this to loop and return all the values instead of having to call by index
const dataValues = data.map((obj, idx) => obj["path" + (idx + 1)])
console.log(dataValues)
Use a for...of to iterate over the array, and then push the value to a new array.
const data=[{path1:"uploads\\20211115000755-package.json"},{path2:"uploads\\20211115012255-index.html"},{path3:"uploads\\20211115014342-dataServerMid.js"}];
const arr = [];
for (const obj of data) {
const [value] = Object.values(obj);
arr.push(value);
}
console.log(arr);
Or you can use map.
const data=[{path1:"uploads\\20211115000755-package.json"},{path2:"uploads\\20211115012255-index.html"},{path3:"uploads\\20211115014342-dataServerMid.js"}];
const arr = data.map(obj => {
const [value] = Object.values(obj);
return value;
});
console.log(arr);
Use for loop for iterate data
const data = [{
"path1": "uploads\\20211115000755-package.json"
}, {
"path2": "uploads\\20211115012255-index.html"
}, {
"path3": "uploads\\20211115014342-dataServerMid.js"
}]
const dataValues = [];
for(var i = 0; i < data.length; i++)
{
dataValues.push(Object.values(data[i]).toString())
}
console.log(dataValues)
This may help You. Try it out..
function nestedLoop(obj) {
const res = {};
function recurse(obj, current) {
for (const key in obj) {
let value = obj[key];
if(value != undefined) {
if (value && typeof value === 'object') {
recurse(value, key);
} else {
// Do your stuff here to var value
res[key] = value;
}
}
}
}
recurse(obj);
return res;
}

how to change a value inside a array of obejcts

My array looks like,
[
{
"lat":68.40928899869893,
"lng":39.548560173006884
},
{
"lat":45.35600542155823,
"lng":32.5203664592608
},
{
"lat":48.94054322456003,
"lng":102.45089391103468
},
{
"lat":70.14969277620159,
"lng":96.8283389400378
}
]
I need to change the lat and lng to Lat and Long
What I tried,
coords[0].map((coord) => {
coord.replace("lat", "Lat");
coord.replace("lng", "long");
});
.map() is the right tool. But instead of thinking of this as modifying or replacing properties on each object, think of it has projecting the array into a new array. For example:
const myArr = [
{
"lat":68.40928899869893,
"lng":39.548560173006884
},
{
"lat":45.35600542155823,
"lng":32.5203664592608
},
{
"lat":48.94054322456003,
"lng":102.45089391103468
},
{
"lat":70.14969277620159,
"lng":96.8283389400378
}
];
const newArr = myArr.map(c => ({
Lat: c.lat,
Long: c.lng
}));
console.log(newArr);
So each iteration of .map() doesn't change the object, it creates a new object in whatever structure you like.
You can achieve this using the array map() function
const cords = [
{
"lat":68.40928899869893,
"lng":39.548560173006884
},
{
"lat":45.35600542155823,
"lng":32.5203664592608
},
{
"lat":48.94054322456003,
"lng":102.45089391103468
},
{
"lat":70.14969277620159,
"lng":96.8283389400378
}
]
const newCords = cords.map((cord) => ({Lat: cord.lat, Long: cord.lng}))
console.log(newCords);
In case you want to modify the original array as well.
coords.map(coord => {
let [lat, lng] = [coord.lat, coord.lng];
delete coord.lat;
delete coord.lng;
coord['Lat'] = lat;
coord['long'] = lng;
return coord;
});
This is one way of changing property names
let arr = [
{
"lat":68.40928899869893,
"lng":39.548560173006884
},
{
"lat":45.35600542155823,
"lng":32.5203664592608
},
{
"lat":48.94054322456003,
"lng":102.45089391103468
},
{
"lat":70.14969277620159,
"lng":96.8283389400378
}
]
arr.forEach(obj => {
Object.keys(obj).forEach(prop => {
if (prop === 'lng') {
obj["long"] = obj[prop];
delete obj[prop];
}
if (prop === 'lat') {
obj["Lat"] = obj[prop];
delete obj[prop];
}
});
});
console.log(arr)
A solution to update your original is as below
Logic
Loop through the array
Assign the value of lat from that object to Lat and lng to long in the same object
Delete lat and lng keys from the object
const cooordinates = [
{
"lat": 68.40928899869893,
"lng": 39.548560173006884
},
{
"lat": 45.35600542155823,
"lng": 32.5203664592608
},
{
"lat": 48.94054322456003,
"lng": 102.45089391103468
},
{
"lat": 70.14969277620159,
"lng": 96.8283389400378
}
]
cooordinates.forEach((node) => {
node['Lat'] = node['lat'];
node['long'] = node['lng'];
delete node['lat'];
delete node['lng'];
});
console.log(cooordinates);

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

Summarize count of occurrences in an array of objects with Array#reduce

I want to summarize an array of objects and return the number of object occurrences in another array of objects. What is the best way to do this?
From this
var arrayOfSongs = [
{"title":"Blue","duration":161.71,"audioUrl":"/assets/music/blue","playing":false,"playedAt":"2016-12-21T22:58:55.203Z"},
{"title":"Blue","duration":161.71,"audioUrl":"/assets/music/blue","playing":false,"playedAt":"2016-12-21T22:58:55.203Z"},
{"title":"Blue","duration":161.71,"audioUrl":"/assets/music/blue","playing":false,"playedAt":"2016-12-21T22:58:55.203Z"},
{"title":"Green","duration":161.71,"audioUrl":"/assets/music/blue","playing":false,"playedAt":"2016-12-21T22:58:55.203Z"}
];
To this
var newArrayOfSongs = [
{"title": "Blue", "playCount": 3 },
{"title": "Green", "playCount": 1}
]
I have tried
arrayOfSongs.reduce(function(acc, cv) {
acc[cv.title] = (acc[cv.title] || 0) + 1;
return acc;
}, {});
}
But it returns an object:
{ "Blue": 3, "Green": 1};
You should pass the initial argument to the reduce function as an array instead of object and filter array for the existing value as below,
Working snippet:
var arrayOfSongs = [
{"title":"Blue","duration":161.71,"audioUrl":"/assets/music/blue","playing":false,"playedAt":"2016-12-21T22:58:55.203Z"},
{"title":"Blue","duration":161.71,"audioUrl":"/assets/music/blue","playing":false,"playedAt":"2016-12-21T22:58:55.203Z"},
{"title":"Blue","duration":161.71,"audioUrl":"/assets/music/blue","playing":false,"playedAt":"2016-12-21T22:58:55.203Z"},
{"title":"Green","duration":161.71,"audioUrl":"/assets/music/blue","playing":false,"playedAt":"2016-12-21T22:58:55.203Z"}
];
var newArrayOfSongs = arrayOfSongs.reduce(function(acc, cv) {
var arr = acc.filter(function(obj) {
return obj.title === cv.title;
});
if(arr.length === 0) {
acc.push({title: cv.title, playCount: 1});
} else {
arr[0].playCount += 1;
}
return acc;
}, []);
console.log(newArrayOfSongs);
To build on what you already have done, the next step is to "convert" the object to an array
var arrayOfSongs = [
{"title":"Blue","duration":161.71,"audioUrl":"/assets/music/blue","playing":false,"playedAt":"2016-12-21T22:58:55.203Z"},
{"title":"Blue","duration":161.71,"audioUrl":"/assets/music/blue","playing":false,"playedAt":"2016-12-21T22:58:55.203Z"},
{"title":"Blue","duration":161.71,"audioUrl":"/assets/music/blue","playing":false,"playedAt":"2016-12-21T22:58:55.203Z"},
{"title":"Green","duration":161.71,"audioUrl":"/assets/music/blue","playing":false,"playedAt":"2016-12-21T22:58:55.203Z"}
];
var obj = arrayOfSongs.reduce(function(acc, cv) {
acc[cv.title] = (acc[cv.title] || 0) + 1;
return acc;
}, {});
// *** added code starts here ***
var newArrayOfSongs = Object.keys(obj).map(function(title) {
return {
title: title,
playCount:obj[title]
};
});
console.log(newArrayOfSongs);
I recommend doing this in two stages. First, chunk the array by title, then map the chunks into the output you want. This will really help you in future changes. Doing this all in one pass is highly complex and will increase the chance of messing up in the future.
var arrayOfSongs = [
{"title":"Blue","duration":161.71,"audioUrl":"/assets/music/blue","playing":false,"playedAt":"2016-12-21T22:58:55.203Z"},
{"title":"Blue","duration":161.71,"audioUrl":"/assets/music/blue","playing":false,"playedAt":"2016-12-21T22:58:55.203Z"},
{"title":"Blue","duration":161.71,"audioUrl":"/assets/music/blue","playing":false,"playedAt":"2016-12-21T22:58:55.203Z"},
{"title":"Green","duration":161.71,"audioUrl":"/assets/music/blue","playing":false,"playedAt":"2016-12-21T22:58:55.203Z"}
];
function chunkByAttribute(arr, attr) {
return arr.reduce(function(acc, e) {
acc[e[attr]] = acc[e[attr]] || [];
acc[e[attr]].push(e);
return acc;
}, {});
}
var songsByTitle = chunkByAttribute(arrayOfSongs, 'title');
var formattedOutput = Object.keys(songsByTitle).map(function (title) {
return {
title: title,
playCount: songsByTitle[title].length
};
});
There, now everything is named according to what it does, everything does just one thing, and is a bit easier to follow.
https://jsfiddle.net/93e35wcq/
I used a set object to get the unique track titles, then used Array.map to splice those and return a song object that contains play count inside the track title.
The Data:
var arrayOfSongs = [{
"title": "Blue",
"duration": 161.71,
"audioUrl": "/assets/music/blue",
"playing": false,
"playedAt": "2016-12-21T22:58:55.203Z"
}, {
"title": "Blue",
"duration": 161.71,
"audioUrl": "/assets/music/blue",
"playing": false,
"playedAt": "2016-12-21T22:58:55.203Z"
}, {
"title": "Blue",
"duration": 161.71,
"audioUrl": "/assets/music/blue",
"playing": false,
"playedAt": "2016-12-21T22:58:55.203Z"
}, {
"title": "Green",
"duration": 161.71,
"audioUrl": "/assets/music/blue",
"playing": false,
"playedAt": "2016-12-21T22:58:55.203Z"
}];
The Function:
function getPlayCount(arrayOfSongs) {
let songObj = {};
let SongSet = new Set();
arrayOfSongs.map(obj => (SongSet.has(obj.title)) ? true : SongSet.add(obj.title));
for (let songTitle of SongSet.values()) {
songObj[songTitle] = {
playCount: 0
};
arrayOfSongs.map(obj => (obj.title === songTitle) ? songObj[songTitle].playCount++ : false)
}
return songObj;
}
console.log(getPlayCount(arrayOfSongs));
Which isn't exactly what you wanted formatting wise, but if you're married to it, this will do the trick:
function getPlayCount(arrayOfSongs) {
let songObj = {};
let SongSet = new Set();
arrayOfSongs.map(obj => (SongSet.has(obj.title)) ? true : SongSet.add(obj.title));
for (let songTitle of SongSet.values()) {
songObj[songTitle] = 0;
arrayOfSongs.map(obj => (obj.title === songTitle) ? songObj[songTitle]++ : false)
}
return songObj;
}
console.log(getPlayCount(arrayOfSongs));
https://jsfiddle.net/93e35wcq/1/

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