Lodash create an object from a collection - javascript

With the following array;
var arr = [
{"name": "blah"},
{"version": "v1.0.0"},
...
]
I would like to create the following object with lodash;
var obj = {
"name": "blah",
"version": "v1.0.0",
...
}
P.S. Duplicates don't matter as there won't be any here.

Here is a solution using plain JavaScript.
References:
Object.assign can be used to concatenate Objects({}).
Array.prototype.reduce can be used to minimize the Array([]) values.
var arr = [{
"name": "blah"
}, {
"version": "v1.0.0"
}];
var obj = arr.reduce(function(o, v) {
return Object.assign(o, v);
}, {});
console.log(obj);

Why use lodash when you can do it in pure js?
var arr = [
{
"name": "blah"
},
{
"version": "v1.0.0"
}
]
var obj = arr.reduce(function(acc, val) {
var key = Object.keys(val)[0];
acc[key] = val[key];
return acc;
}, {})
console.log(obj)

Lodash implementation.
var arr = [{
"name": "name"
}, {
"version": "v1.0.0"
},{
"manager": "manager"
}];
var result = _.reduce(arr, function(object, value) {
return _.assign(object, value);
}, {});
console.log(result);

Related

How to convert object into array in Javascript

I have the below object obj(coming as a JSON response):
var obj = {
0: {
note: 'test1',
id: 24759045,
createTimeStamp: '2022-08-01T17:05:36.750Z',
},
1: {
note: 'test2',
id: 24759045,
createTimeStamp: '2022-08-01T17:05:51.755Z',
},
note: 'test1',
id: 24759045,
createTimeStamp: '2022-08-01T17:05:36.750Z',
};
I only want the objects with numbers("0" , "1" .. so on) to be pushed in an array.
Below is what I am trying to do:
let items = [];
for (var prop in obj) {
items.push(obj[prop]);
}
console.log(items);
// expected output:
[
{
note: 'test1',
id: 24759045,
createTimeStamp: '2022-08-01T17:05:36.750Z',
},
{
note: 'test2',
id: 24759045,
createTimeStamp: '2022-08-01T17:05:51.755Z',
},
]
Any pointers would be highly appreciated.
A few things to consider here.
Are the numeric keys ordered?
Does the order matter?
Are the numeric keys an index of the item in the array?
Are there any gaps in the numeric keys?
First solution, assuming that the numeric keys are the index in the array.
const items = Object.keys(obj).reduce((acc, key) => {
const index = parseInt(key);
if (Number.isNaN(index)) {
return acc;
}
acc[index] = obj[key];
return acc;
}, []);
Second solution, assuming that order matters, but that the numeric keys are not guaranteed to be contiguous.
const items = Object.keys(obj)
.filter((key) => Number.isNaN(parseInt(key)) === false)
.sort()
.map((key) => obj[key]);
Keep in mind that Object.keys does not guarantee that the keys are ordered alpha-numerically. So if order matters, then you have to sort them.
Third solution, if order doesn't matter.
const items = Object.keys(obj)
.filter((key) => Number.isNaN(parseInt(key)) === false)
.map((key) => obj[key]);
var result = [];
var obj = {
"0": {
"note": "test1",
"id": 24759045,
"createTimeStamp": "2022-08-01T17:05:36.750Z"
},
"1": {
"note": "test2",
"id": 24759045,
"createTimeStamp": "2022-08-01T17:05:51.755Z"
},
"note": "test1",
"id": 24759045,
"createTimeStamp": "2022-08-01T17:05:36.750Z"
}
for (var i in obj)
result.push(obj[i]);
$('#result').html(JSON.stringify(result));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="result"></div>
You can achieve this by doing the following steps.
Copied your object below -->
var obj = {
"0": {
"note": "test1",
"id": 24759045,
"createTimeStamp": "2022-08-01T17:05:36.750Z"
},
"1": {
"note": "test2",
"id": 24759045,
"createTimeStamp": "2022-08-01T17:05:51.755Z"
},
"note": "test1",
"id": 24759045,
"createTimeStamp": "2022-08-01T17:05:36.750Z"
}
Created new js array -->
var result = [];
Code -->
for (var i in obj)
result.push(obj[i]);
Find the solution from link below as well --> :) :)
https://jsfiddle.net/kavinduxo/95qnpaed/
I think you'll need to get the keys of the object, filter out the non-numeric ones, then map each key to the obj[key]:
var obj={"0":{"note":"test1","id":24759045,
"createTimeStamp":"2022-08-01T17:05:36.750Z"},"1":{"note":"test2","id":24759045,
"createTimeStamp":"2022-08-01T17:05:51.755Z"},
"note":"test1","id":24759045,"createTimeStamp":"2022-08-01T17:05:36.750Z"};
console.log(
Object.keys(obj)
.filter((key) =>!Number.isNaN(parseInt(key)))
.map((key) => obj[key])
)

Filter array based on dynamic parameter

Say I have an array of json objects which looks like below:
var codes = [{
"code_id": "1",
"code_name": "code 1", ,
}, {
"code_id": "2",
"code_name": "code889",
},
// ... () ...
]
How can I filter codes array based on dynamic input parameter?
So I am looking for a generic function which will take input array and key and value as i/p.
var filteredCodes = getFilteredCodes(codes, "code_id", 2);
Thanks.
Use Array.prototype.filter to filter out the result - see demo below:
var codes = [{"code_id": "1","code_name": "code 1"}, {"code_id": "2","code_name": "code889"}];
function getFilteredCodes(array, key, value) {
return array.filter(function(e) {
return e[key] == value;
});
}
var filteredCodes = getFilteredCodes(codes, "code_id", 2);
console.log(filteredCodes);
You could use Array#filter with the key and value.
function getFilteredCodes(array, key, value) {
return array.filter(function (o) {
return o[key] === value;
});
}
var codes = [{ "code_id": "1", "code_name": "code 1", }, { "code_id": "2", "code_name": "code889" }],
filteredCodes = getFilteredCodes(codes, "code_id", "2");
console.log(filteredCodes);
function getFilteredCodes(poolArray,key,val){
return poolArray.filter(function(item,ind){
return item[key]==val;
});
}
Or the function in an only line with arrow notation
var codes = [{ "code_id": "1", "code_name": "code 1", }, { "code_id": "2", "code_name": "code889" }];
var getFilteredCodes = (array, key, value) => array.filter(x => x[key] === value);
var FilteredCodes = getFilteredCodes(codes, "code_id", "2");
console.log(FilteredCodes);

reducing array elements using underscore.js

I am getting an array of data containing many parameters. For example, the data array is in the below format:
var data = [
{
"name":"pradeep",
"age": "32",
"location": "Bangalore"
},
{
"name":"praveen",
"age": "30",
"location": "Mangalore"
},
{
"name":"Ajay",
"age": "32",
"location": "Hubli"
}
]
I want the above array to be reduced to the below format:
[
{
"name":"pradeep"
},
{
"name":"praveen"
},
{
"name":"Ajay"
}
]
How to get this done using Underscore. I tried using the _.pluck but it fetches only the data and not the key.
You could use pure JavaScript to do it, one way is:
data.map(function(obj) {
return {'name': obj.name};
})
If you'd like to parametrize key that should be kept, you may write function like that:
function filterByKey(arr, key) {
return arr.map(function(obj) {
var newObj = {};
newObj[key] = obj[key];
return newObj;
});
}
and use it like that:
var newData = filterByKey(data, 'name');
Cheers
In native JavaScript, you can do it like:
var data = [{
"name": "pradeep",
"age": "32",
"location": "Bangalore"
}, {
"name": "praveen",
"age": "30",
"location": "Mangalore"
}, {
"name": "Ajay",
"age": "32",
"location": "Hubli"
}];
var newData = data.map(function(d) {
return { name: d.name }
});
console.log(newData)
Underscore is not really required, you can do this..
var newData = data.map(function (x) {
return { name: x.name };
});
but if you really want to use underscore this is the way:
var newData = _.map(data, function (x) {
return { name: x.name };
});
For a strictly underscore JS method you can use _.map combined with _.pick:
var newData = _.map(data, function(d) { return _.pick(d, 'name' })
However using _.pick will not be as efficient as just simply returning { name: d.name } in the _.map callback.
You need to use the map function from Undescore. It's a very popular utility from the functional programming and you can also use it natively in the browser.
With Underscore.js the code looks like this:
_.map(data, function(element) {
return {name: element['name']};
})
You can do it using native JavaScript
var result = [];
data.forEach(function(d){
result.push({'name': d.name}) // d is an iterator
})
You could as use map function to return the key value pair
var result = data.map(function(d){
return {'name': d.name}
})

JSON - array of objects into objects of arrays

I have a series of JSON entries:
[{"num": "1","name_A": "Alex" ,"name_B": "Bob"}, {"num": "2","name_A": "Anne" ,"name_B": "Barbra"}]
I am trying to convert this array of Objects as painlessly as possible into two objects - one with title name_A, and the second with the title name_B. Objects have to contain the title and an array of matching num-name pairs:
[{title: "name_A", names:[{"1", "Alex}, {"2", "Anne"}]}, {title:"name_B", names: [{"1", "Bob"}, {"2", "Barbra"}]}]
At first I tried simply to create two objects by reducing the array of object twice, once for name_A and second time for name_B and later glue everything together:
// get 'names' array
var name_A = objArray.reduce(function(memo, curr) {
memo.push({curr.num, curr.name_A})
return memo;
}, []);
But even this is failing. Why there is no push method for memo if I initialize reduce with an empty array?
And second question, am I on a right track or is there a better way to achieve this?
Comments inline, made a few minor corrections to the expectations.
var input = [{ "num": "1", "name_A": "Alex", "name_B": "Bob" }, { "num": "2", "name_A": "Anne", "name_B": "Barbra" }]
var output = input.reduce(function (a, b) {
// construct new objects and set their properties
var i = {};
i[b.num] = b.name_A;
var j = {};
j[b.num] = b.name_B;
// add them to our collection elements
a[0].names.push(i);
a[1].names.push(j);
return a;
// initializing our collection
}, [{ title: "name_A", names: [] }, { title: "name_B", names: [] }]);
// pretty print our output
console.log(JSON.stringify(output, null, " "))
var input = [{ "num": "1", "name_A": "Alex", "name_B": "Bob" }, { "num": "2", "name_A": "Anne", "name_B": "Barbra" }]
var output = input.reduce(function (a, b) {
// construct new objects and set their properties
var i = {};
i[b.num] = b.name_A;
var j = {};
j[b.num] = b.name_B;
// add them to our collection elements
a[0].names.push(i);
a[1].names.push(j);
return a;
// initializing our collection
}, [{ title: "name_A", names: [] }, { title: "name_B", names: [] }]);
so.log(output)
<pre id="output"></pre>
<script>
var so = {
log: function(o) {
document.getElementById("output").innerHTML = JSON.stringify(o, null, " ")
}
}
</script>
The problem with your code is that { curr.num, curr.name_A } is not a valid object, it's missing the property names. I've added properties num and name in my code below.
var name_A = [];
var name_B = [];
objArray.forEach(function(curr) {
name_A.push({num: curr.num, name: curr.name_a});
name_B.push({num: curr.num, name: curr.name_B});
});
var result = [
{ title: "name_A" }, names: name_A },
( title: "name_B" }, names: name_B }
];
Also, if you want to make an array out of the results of looping over an array, you should use .map rather than .reduce.
Assuming only property num is fixed. All other properties are treated as data, like name_A or name_B.
var a = [{ "num": "1", "name_A": "Alex", "name_B": "Bob" }, { "num": "2", "name_A": "Anne", "name_B": "Barbra" }],
result = [];
a.forEach(function (el) {
var num = el.num;
Object.keys(el).forEach(function (k) {
function tryFindIndexAndSetNames(aa, i) {
if (aa.title === k) {
result[i].names[num] = el[k];
return true;
}
}
if (k !== 'num' && !result.some(tryFindIndexAndSetNames)) {
var o = {};
o[num] = el[k];
result.push({ title: k, names: o });
}
});
});
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');

Change object in array's key name

arr = [
{"id":"1"},
{"id":"2"}
];
For some reason I want to change the "id" to "uid". I am stuck here
arr.forEach(function(i){
});
arr = [{
"id": "1"
},
{
"id": "2"
}
];
arr.forEach(function(i) {
i.uid = i.id;
delete i.id;
});
console.log(arr);
This will modify arr. If you want a copy of arr that has the changed structure, follow Mritunjay's answer.
Just do like bellow:
arr = [{
"id": "1"
},
{
"id": "2"
}
];
arr = arr.map(function(obj) {
return {
"uid": obj.id
}
});
console.log(arr);
Here you go:
arr.map(function (a) {
a.uid=a.id;delete a.id;
return a;
});
This just goes through the array, renames it, and returns the value.
Snippet:
var arr = [{
"id": "1"
}, {
"id": "2"
}];
arr = arr.map(function(a) {
a['uid'] = a['id'];
delete a['id'];
return a;
});
console.log(arr);
You mentiond forEach so here's an answer with it.
arr.forEach(function (a) {
a.uid=a.id;delete a.id;
});
arr = [{
"id": "1"
},
{
"id": "2"
}
];
arr = arr.map(function(item, index) {
// forget about the index, e.g. running from 0 to arr.length - 1
return {
uid: item.id
};
});
console.log(arr);

Categories

Resources