Combine object with array as list of arrays - javascript

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

Related

How do construct ForEach into map in javascript

I have sample JSON in form of
var sample=[{"id":200,"children":[{"value":300,"type":"SINGLE"},{"value":400,"type":"CLASSIC"},{"value":600,"type":"DUAL"}]},{"id":300,"children":[{"value":500,"type":"TRIO"},{"value":600,"type":"MUSICAL"},{"value":700,"type":"UMBRELA"}]}]
var result = [];
sample.forEach(function(e){
let obj = {}
obj.id=e.id
obj['somekey']=e.children[0].value
obj['someanotherkey']=e.children[1].type
result.push(obj);
})
console.log(result)
How do i can achieve same using map es-6
var sample=[{"id":200,"children":[{"value":300,"type":"SINGLE"},{"value":400,"type":"CLASSIC"},{"value":600,"type":"DUAL"}]},{"id":300,"children":[{"value":500,"type":"TRIO"},{"value":600,"type":"MUSICAL"},{"value":700,"type":"UMBRELA"}]}]
var output = sample.map(({ id, children }) => ({ id, ...children[0] }));
console.log(output);
.map() returns an array, so you must set up a variable to hold that result. Then, within the loop, you use return to effectively push items into the array.
var sample=[{"id":200,"children":[{"value":300,"type":"SINGLE"},{"value":400,"type":"CLASSIC"},{"value":600,"type":"DUAL"}]},{"id":300,"children":[{"value":500,"type":"TRIO"},{"value":600,"type":"MUSICAL"},{"value":700,"type":"UMBRELA"}]}];
let result = sample.map(function(e){
let obj = {}
obj.id=e.id;
obj['value']=e.children[0].value;
obj['type']=e.children[0].type
return obj;
});
console.log(result);
If you want to be able to chose the children index:
const getDataChild = (a, i) => a.map(({id, children:ch}) => ({id, ...ch[i]}));
console.log(getDataChild(sample, 0)); // where 0 is the desired index

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

Convert 2D array into an object

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.

Lodash: Extract property, split array, get unique values

In my JS project, I am using Lodash library to Extract property, split array, get unique values.
var taskobj = [
{'taskno':'a', 'team':'1,2'},
{'taskno':'b', 'team':'3,4'},
{'taskno':'c', 'team':'2,4'},
];
//Looping through the object to convert string to array
_.forEach(taskobj, function(value, key) {
taskobj[key].team = _.split(taskobj[key].team,',');
});
// using _.map to extract team and return array
// using _.flatten to flatten array
// using _.uniq to get unique values from flattned array.
return _.uniq(_.flatten(_.map(taskobj,'team')));
// logs - [1,2,3,4]
Is this the most efficient way to achieve this?
you can use reduce and start with a new Set() and add the values of team every time ( then convert it back to an array with the spread operator )
var taskobj = [
{'taskno':'a', 'team':'1,2'},
{'taskno':'b', 'team':'3,4'},
{'taskno':'c', 'team':'2,4'},
];
var result = [...taskobj.reduce((acc, {team}) => {
team.split(',').forEach(e => acc.add(e))
return acc
}, new Set())]
console.log(result)
This can be achieved by using lodash#flatMap with an iteratee that splits the team string into an array, which is then flattened by the mentioned function and then use lodash#uniq to get the final result.
var result = _.uniq(_.flatMap(taskobj, ({ team }) => team.split(',')));
var taskobj = [
{'taskno':'a', 'team':'1,2'},
{'taskno':'b', 'team':'3,4'},
{'taskno':'c', 'team':'2,4'},
];
var result = _.uniq(_.flatMap(taskobj, ({ team }) => team.split(',')));
console.log(result);
.as-console-wrapper{min-height:100%;top:0}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>
Use simpler version
try this
var teams = [];
var taskobj = [
{'taskno':'a', 'team':'1,2'},
{'taskno':'b', 'team':'3,4'},
{'taskno':'c', 'team':'2,4'},
];
taskobj.map(obj => {
var teamSplit = obj.team.split(',');
teams = [...teams, ...teamSplit];
})
var uniqTeams = _.uniq(teams);
console.log('teams', teams);
console.log('uniqTeams', uniqTeams)
JsBin link
http://jsbin.com/bedawatira/edit?js,console

How to store two arrays as a key-value pair in one object in Javascript?

I am trying to store two array's as a key-value pair into an object. Since push does not work with objects how do I achieve this ?
JAvascript
var data = {};
var array1 = ['name', 'lastname'];
var array2 = ['john','doe'];
Desired output:
console.log(data);
data: {
name: john,
lastname: doe
}
You can use Array.prototype.reduce():
var array1 = ['name', 'lastname'];
var array2 = ['john','doe'];
var data = array1.reduce((acc, value, i) => (acc[value] = array2[i], acc), {});
console.log(data);
The second argument to the reduce method is the initial value. The first argument is an arrow function which gets called once for each element of array1. acc is either the initial value, or the return value of the previous call. value is the current element of array1. i is the index of the current element. This function assigns the matching element of array2 to a property of acc, and returns acc using the comma operator.
You could utilize thisArg for the wanted object and assign key and value of the same index.
var data = {},
array1 = ['name', 'lastname'],
array2 = ['john','doe'];
array1.forEach(function (k, i) {
this[k] = array2[i];
}, data);
console.log(data);
You can use reduce method for this, which accepts a callback method as parameter.
var array1 = ['name', 'lastname'];
var array2 = ['john','doe'];
var data=array1.reduce(function(obj,elem,index){
obj[elem]=array2[index];
return obj;
},{});
console.log(data);

Categories