Convert 2D array into an object - javascript

How can I convert this
[["name", "oni"], ["age",2]]
to
[{name:"oni"}, {age:2}]

You can use .map() to iterate over array and returned value in desired (object) format:
let data = [["name", "oni"], ["age",2]];
let result = data.map(([key, value]) => ({[key]: value}));
console.log(result);

new_array = your_array.map((entry)=>{
return {[entry[0]]: entry[1]}
})
console.log(new_array)

Assuming the properties keys are unique why not create a single object with reduce instead? A single object is much easier to manipulate than an array of objects with one property apiece.
const arr = [["name", "oni"], ["age",2]];
const obj = arr.reduce((acc, c) => {
acc[c[0]] = c[1];
return acc;
}, {});
console.log(obj);
Then just grab the values with dot notation: obj.name, for example.

Related

How i can to convert array to object of array in react?

I have a data in array
["Avengers","Batman","Spiderman","IronMan"]
how I can to covert to below
{"Avenger":"Avenger","Batmane":"Batman","Spiderman":"Spiderman","Ironman":"Ironman"}
You can do it like this:
let arr = ["Avengers","Batman","Spiderman","IronMan"];
let obj = arr.reduce((acc, item)=> ({...acc, [item]: item}) , {});
console.log(obj);
Someone else mentioned reduce, but I recommend against, copying objects at every iteration.
Here's a more performant approach.
const arr = ["Avengers","Batman","Spiderman","IronMan"];
const obj = {};
for (const el of arr) {
obj[el] = el;
}
console.log(obj);
You can use reduce to convert array to object.
You can see some examples in here Convert Array to Object

How can I group by the array using lodash or javascript

An Array is as follows:
let names = [
'Aditya',
'Aditya',
'Aditya',
'Abhi',
'Abhi',
'goyal'
]
I want to use lodash function and convert the names array which will return me as
[
Aditya(3),
Abhi(2),
goyal(1)
]
You can use _.countBy() to get an object of names with count, or a _.groupBy() if you want an object of names with arrays.
An array of arrays using _.groupBy() and _.values():
const names = ["Aditya","Aditya","Aditya","Abhi","Abhi","goyal"]
const result = _.values(_.groupBy(names))
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
And object of counts with _.countBy:
const names = ["Aditya","Aditya","Aditya","Abhi","Abhi","goyal"]
const result = _.countBy(names)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
Update - to get an array of strings that combine the key and value, you can use _.countBy(), and then _.map() it (lodash's _.map() works on objects as well).
const names = ["Aditya","Aditya","Aditya","Abhi","Abhi","goyal"]
const result = _.map(_.countBy(names), (v, k) => `${k}(${v})`)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
1) _.countBy the names to produce an object with name/count as the key/value.
2) Use _.entries to convert the object to a set of nest entry arrays.
3) _.map over the entries to produce the required output.
const names = ["Aditya","Aditya","Aditya","Abhi","Abhi","goyal"]
const toString = ([name, count]) => `${name}(${count})`;
const entries = _.entries(_.countBy(names));
const result = _.map(entries, toString);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
Alternatively you can use vanilla JS to achieve the same thing in (almost) the same amount of code using reduce, Object.entries, and map.
const names = ["Aditya","Aditya","Aditya","Abhi","Abhi","goyal"]
const counts = names.reduce((acc, c) => {
return acc[c] = (acc[c] || 0) + 1, acc;
}, {});
const toString = ([name, count]) => `${name}(${count})`;
const entries = Object.entries(counts);
const result2 = entries.map(toString);
console.log(result2);

How to get the matching second array of object in es6

I have two array of objects: - better solution
array1= [{id:1,name:"samsung"},{id:2,name:"nokia"},{id:3,name:"Lg"}];
array2 = [{id:5,name:"samsung"},{id:2,name:"panasonics"},{id:7,name:"Lg"}];
Expected output be:
if first array and second array id matches means take the second array name
in above example id 2 matches and we need id:2,name: panasonics.
o/p:
[{id:1,name:"samsung"},{id:2,name:"panasonics"},{id:3,name:"Lg"},{id:5,name:"samsung"},{id:7,name:"Apple"}]
Combine the arrays using Array.concat(), reduce them into a Map by id, and then convert the Map's values to an array with Array.from():
const unionBy = (field, ...arrays) => Array.from(
[].concat(...arrays)
.reduce((r, o) => r.set(o.id, o), new Map)
.values()
);
const array1 = [{id:1,name:"samsung"},{id:2,name:"nokia"},{id:3,name:"Lg"}];
const array2 = [{id:5,name:"samsung"},{id:2,name:"panasonics"},{id:7,name:"Lg"}];
const result = unionBy('id', array1, array2);
console.log(result);
You can use a simple .forEach() loop like below (you can also use a for loop if you want, but .forEach() is easier).
This code loops through array1, and loops through array2 in that loop. It then checks if the ids are the same. If there are, the name is appended to result.
const array1= [{id:1,name:"samsung"},{id:2,name:"nokia"},{id:3,name:"Lg"}];
const array2 = [{id:5,name:"samsung"},{id:2,name:"panasonics"},{id:7,name:"Lg"}];
let result = [];
array1.forEach(e1 => {
array2.forEach(e2 => {
if (e1.id == e2.id) {
result.push(e2.name);
}
});
});
console.log(result);
Use map() and concat() like the following code
array1= [{id:1,name:"samsung"},{id:2,name:"nokia"},{id:3,name:"Lg"}];
array2 = [{id:5,name:"samsung"}, {id:2,name:"panasonics"},{id:7,name:"Lg"}];
var array3=array1.map(function(i,v){
if(array2[v].id==i.id){
return array2[v]
}
else return i
})
array4=array3.concat(array2);
console.log(array4);

Transform from string array to hashmap in Lodash

What is the most precise way to transform from this
["access","edit","delete"]
to this
{access:true, edit:true, update:true}
Currently i loop to assign each value in object but i wonder if lodash already provide function for this
Use reduce(). This can all be done with a simple one-liner, that doesn't require any libraries:
const input = ["access","edit","delete"];
console.log(
input.reduce((obj, key) => { obj[key] = true; return obj; }, {})
);
With the new es6 spread syntax, you can even make this easier:
const input = ["access","edit","delete"];
console.log(
input.reduce((obj, key) => ({...obj, [key]: true}), {})
);
LODASH
You can map it to a array of entries and then simply use fromPairs of lodash
_.fromPairs(input.map(k=>[k, true]))
var input = ["access","edit","delete"];
var res = _.fromPairs(input.map(k=>[k,true]));
console.log(res);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
ES6
You can map your input to a key (your each input) value (true) pair of objects and assign them.
Object.assign( ...input.map(k=>({[k]: true})))
var input = ["access","edit","delete"]
var res = Object.assign( ...input.map(k=>({[k]: true})));
console.log(res);
In case you want a Map object you can map your input to entries (as used in lodash example) and simply construct a new Map like
new Map(input.map(k=>[k, true]))
No need to import a library for something so simple, just reduce the array of keys into an object indexed by those keys:
const input = ["access","edit","delete"];
const output = input.reduce((a, key) => Object.assign(a, {[key]: true}), {});
console.log(output);
Or, assigning to the property of the accumulator rather than using Object.assign:
const input = ["access","edit","delete"];
const output = input.reduce((a, key) => {
a[key] = true;
return a;
}, {});
console.log(output);
If you absolutely want to use lodash (As opposed to the above vanilla javascript reduce() answers), you can use _.mapValues() to accomplish this:
const input = ["access","edit","delete"];
const output = _.mapValues(_.keyBy(input), () => true)
console.log(output);
<script src="https://cdn.jsdelivr.net/npm/lodash#4.17.11/lodash.min.js" integrity="sha256-7/yoZS3548fXSRXqc/xYzjsmuW3sFKzuvOCHd06Pmps=" crossorigin="anonymous"></script>

Combine object with array as list of arrays

I have an Object as
var a ={
demo:[1,2,3],
demo1:[test1,test2,test3]
}`
I want to convert the above object into array of objects
var a = [{"demo":"1", "demo1":"test1"},{"demo":"2", "demo1":"test2"},{"demo":"3", "demo1":"test3"}];`
can anyone help on this??
Iterate on the first array - demo, using Array#map function and then using the index of the first item access the demo1 appropriate item.
const a = {
demo: [1, 2, 3],
demo1: ['test1', 'test2', 'test3']
};
const mapped = a.demo.map((item, index) => ({ demo: item, demo1: a.demo1[index] }));
console.log(mapped);
You can use array#reduce to iterate through your array and using Object#keys() you can get the key of each object then iterate through each key and add to an accumulator object.
var a = [{"demo":"1", "demo1":"test1"},{"demo":"2", "demo1":"test2"},{"demo":"3", "demo1":"test3"}],
result = a.reduce((r,o) => {
Object.keys(o).forEach(k => {
r[k] = r[k] || [];
r[k].push(o[k]);
});
return r;
},{});
console.log(result);

Categories