Lodash merge array with dictionary object key values - javascript

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

Related

Javascript - Create and populate associative array containing sub arrays

I'm trying to collate some data. I would like to populate an array containing sub arrays, for example, I have some json data that I am iterating over:
{
"name": "name1",
"prices": "209.67"
},
{
"name": "name1",
"prices": "350"
},
{
"name": "name2",
"price": "195.97"
},
I would like to create an array that ends up looking something like the following:
myArray['name1']prices[0] = 209.67,
prices[1] = 350,
['name2']prices[0] = 195.97
I thought that the code below would achieve what I wanted but it doesn't work. It throws an exception. It doesn't seem to recognise the fact that the prices are an array for a given index into the main array. Instead the prices appear at the same level as the names. I want the main array for a given name to contain an inner array of prices.. Does anybody have any idea how I could modify to make this work?
function doStuff() {
var cryptoData = getData();
var datasetValues = {};
datasetValues.names = [];
datasetValues.names.prices = [];
for (var result = 0; result < cryptoData.length; result++) {
var data = cryptoData[result];
if (datasetValues.names.indexOf(data.cryptoname) === -1)
{
datasetValues.names.push(data.cryptoname);
}
// This works
//datasetValues.names.prices.push(data.prices);
// This doesn't!
datasetValues.cryptoNames[data.cryptoname].prices.push(data.prices);
}
}
You could reduce the array by using an object and take a default object if the property is not set. Then push the price.
var data = [{ name: "name1", price: "209.67" }, { name: "name1", price: "350" }, { name: "name2", price: "195.97" }],
result = data.reduce((r, { name, price }) => {
r[name] = r[name] || { name, prices: [] };
r[name].prices.push(+price);
return r;
}, Object.create(null));
console.log(result);
Try this
function parseData(input){
return input.reduce(function(o,i){
o[i.name] = {};
if(!o[i.name]['prices']){
o[i.name]['prices'] = [];
}
o[i.name]['prices'].push(i.prices);
return o;
},{});
}

Pull properties from an object by their name into a different object

i'm doing a project in VueJS and i have an array of data, which consists of a number of objects.
These objects are pulled from a PHP Backend and consist of values like
id: 2123
name: "Name Value"
status: "active"
account_id: "2KGGALS2353255"
Imagine i want to split these by the keys names into a similar array but i want to have a parent object that consists of two child objects
[
0: {
core: {
id: 2123
name: "Name Value"
},
extra: {
status: "active",
account_id: "2KGGALS2353255"
}
]
The question is how can i achieve this with Javascript? I don't really want to modify the data in PHP beforehand unless this is something very unadvised to do in Javascript.
I can use VueJS and Lodash.
I was looking for lodash's pick() method.
https://lodash.com/docs/4.17.4#pick
This should work for your purpose
function separate(obj, keys) {
let target = {}, rest = {};
Object.keys(obj).forEach(function(key) {
if (keys.includes(key)) {
target[key] = obj[key];
} else {
rest[key] = obj[key];
}
});
return { target: target, rest: rest };
}
let stuff = {
id: 2123,
name: "Name Value",
status: "active",
account_id: "2KGGALS2353255"
};
let separated = separate(stuff, ['id', 'name']);
console.log({
core: separated.target,
extra: separated.rest
});
Using ES6's object destructuring, and the object rest spread proposal, which requires a babel transform, you can Array#map the array into a new array of objects in the required format:
const arr = [{"id":1,"name":"Name1","status":"active","account_id":"2KGGALS2353255"},{"id":2,"name":"Name2","status":"active","account_id":"4ABCLS2353255"},{"id":3,"name":"Name3","status":"active","account_id":"6LMNALS2353255"}];
const result = arr.map(({ id, name, ...extra }) => ({
core: {
id,
name
},
extra
}));
console.log(result);
You can do the same thing using lodash's _.pick() to the get the core, and _.omit() to get the extra:
var arr = [{"id":1,"name":"Name1","status":"active","account_id":"2KGGALS2353255"},{"id":2,"name":"Name2","status":"active","account_id":"4ABCLS2353255"},{"id":3,"name":"Name3","status":"active","account_id":"6LMNALS2353255"}];
var result = arr.map(function(obj) {
return {
core: _.pick(obj, ['id', 'name']),
extra: _.omit(obj, ['id', 'name'])
};
});
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

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

Is there a method to split an array of objects into groups?

Suppose I have an array of objects with some sort of groupable key:
var people = [
{ 'name':'Alice', 'gender': 'female' },
{ 'name':'Bob', 'gender': 'male' },
{ 'name':'Jeremy', 'gender': 'male' },
{ 'name':'Jess', 'gender': 'female' },
{ 'name':'Seymour', 'gender': 'female' },
];
Is there a (native) function/method that can be applied to the array to 'unzip' the array into two arrays, like so:
boysAndGirls = people.[**something**]('gender');
That could result in:
{
'male': [ ... ],
'female': [ ... ]
}
or even:
[
[ {Bob, ...}, {Jeremy, ...}, {Seymour, ...} ], // 'males' array
[ {Alice, ...}, {Jess, ...} ] // 'female' array
]
I could write this algorithm myself, but I really just want to know if there is a native array method -- or one that might exist in another language that could be polyfilled in?
const groupByAge = users.reduce((p,c) =>{
const genKey = Math.floor(c.age/10);
const key = `${genKey}0- ${genKey}9`;
if(!p[key]){
p[key] =[];
}
p[key].push(c);
return p;
}, {})
console.log(groupByAge);
There is no such method in JavaScript. Ruby has it in Enumerator#group_by:
people.group_by { |person| person['gender'] }
and it is easy enough to write in JavaScript as well. In fact, some libraries have it already, e.g. Lodash.
_.groupBy(people, function(person) {
return person['gender'];
});
If you write it yourself, you can customise it a bit:
function groupByProp(array, prop) {
var result = {};
array.forEach(function(item) {
var val = item[prop];
if (!result[val]) result[val] = [item];
else result[val].push(item);
});
return result;
}
groupByProp(people, 'gender');
There is not a native Javascript function for this but you can use the following code:
var originalArray = [1,2,3,4,5,6,7,8,9];
var splitArray = function (arr, size) {
var arr2 = arr.slice(0),
arrays = [];
while (arr2.length > 0) {
arrays.push(arr2.splice(0, size));
}
return arrays;
}
splitArrays = splitArray(originalArray, 2);
console.log(splitArrays);
The nearest thing I can think of off the top of my head for a native solution is to use reduce. It's not as simple as what you are looking for but it works:
var boysAndGirls = people.reduce(function(obj, item) {
obj[item.gender].push(item.name);
return obj;
}, {male: [], female: []});

Turning an array into an array of objects with Underscore.js?

I have an array:
var countries = ['Austria', 'America', 'Australia'];
I know you can turn that into an object with Underscore.js like this:
_.object(['name', 'name2', 'name3'], countries));
How can I turn the array into an array of objects that looks like this?
var countriesObject = [
{ name: 'Austria' },
{ name: 'America' },
{ name: 'Australia' }
];
(with all the keys named name).
No need to use Underscore.js for that. You can do it with plain javascript:
var new_arr = [];
countries.forEach(function(country) {
var new_obj = {};
new_obj.name = country;
new_arr.push(new_obj);
});
console.table(new_arr);
var countriesObject = _.map (countries,function (country){
return {
name: country
}
}

Categories

Resources