arr1 = [{name : xyz}, {age: 26}, {sex : m}]
arr2 = [{place: somwhere}, {std: 6}]
result should be
arr3 =[
{name : xyz, place: somwhere, std: 6},
{age: 26 , place: null , std: null},
{sex : m, place: null , std: null}
]
Try this.
You only have two data types there strings and number, you can't merge undefined data types of objects.
var arr1 = [{ name: "xyz" }, { age: 26 }, { sex: "m" }]
var arr2 = [{ place: "somwhere" }, { std: 6 }]
var arr3 = [];
arr3.push(arr1, arr2)
console.log(arr3)
Try this, return a new Array object:
Object.assign({}, arr1, arr2,arr3)
You can merge the two arrays like this:
const res = [...arr1, ...arr2]
but that will give you an array like this as result
[ {name: "xyz"}, {age: 26}, {sex: "m"}, {place: "somwhere"}, {std: 6} ]
Which is not what you want.
You could also merge one of the items from the first array with the second, like this
const res2 = arr1.map( (key, index) => [arr1[index], ...arr2])
console.log(res2)
But that will give you a result like this:
[
[ {name: "xyz"}, {place: "somwhere"}, {std: 6}],
[ {age: 26}, {place: "somwhere"}, {std: 6}],
[ {sex: "m"}, {place: "somwhere"}, {std: 6}]
]
Which is also not exactly what you wanted.
If you want to achieve exactly the result you want to, I guess you would have to have some sort of logic between the the two arrays, for instance having the values you want merged in different indexes of the second array:
const arr1 = [{name : 'xyz'}, {age: 26}, {sex : 'm'}]
const arr2 = [ [{place: 'somwhere'}, {std: 6}], [{place: null}, {std: null}], [{place:null}, {std: null}]]
const res = arr1.map( (key, index) => [arr1[index], ...arr2[index]])
console.debug('res:',res)
This gives you the exact result you want, but has a different setup. If you say more about the logic behind, there might be a better answer.
I will put the logic in java, convert it to javascript
Object[] arr1= {"benz",26,'m'};
Object[] arr2= {"somewhere",6};
Object[][] arr3= new Object[arr1.length][arr1.length];
for(int r=0;r<arr3.length;r++)
{
for(int c=0;c<1;c++)
{
if(r!=0)
System.out.println("name : "+arr1[r]+", place : "+null+", std : "+null);
else
System.out.println("name : "+arr1[r]+", place : "+arr2[c]+", std : "+arr2[c+1]);
}
}
}
Related
Let's say I got an array of object like this
const arr = [
{name: 'John', age: 15},
{name: 'Max', age: 17},
{name: 'Tom', age: 11},
]
How can I take just the object containing Max, 17?
This would be the result
b = [{ name: Max, age: 17 }]
or better
c = { name: Max, age: 17 }
Reduce the array to the object with highest age:
const arr = [{"name":"John","age":15},{"name":"Max","age":17},{"name":"Tom","age":11}]
const result = arr.reduce((acc, o) => !acc || o.age > acc.age ? o : acc, null)
console.log(result)
I'm using null as the default value for the Array.reduce() to prevent an error if the array is empty. However, you can check for an empty array beforehand as well:
const findMaxAge = arr => arr.length
? arr.reduce((acc, o) => o.age > acc.age ? o : acc)
: null
const arr = [{"name":"John","age":15},{"name":"Max","age":17},{"name":"Tom","age":11}]
console.log(findMaxAge(arr))
console.log(findMaxAge([]))
You can sort by age first, then the object with the highest age value will be at the start of the list:
const a = [
{name: "John", age: 15},
{name: "Max", age: 17},
{name: "Tom", age: 11},
]
const sortedByAge = a.sort((a,b) => b.age - a.age);
const highestAge = sortedByAge[0];
console.log(highestAge);
hope this code helping you
const a = [{name: 'John', age: 15},
{name: 'Max', age: 17},
{name: 'Tom', age: 11},];
const result = a.reduce((p, c) => p.age > c.age ? p : c);
console.log(result);
Using the Array.prototype.reduce() is a clean way.
this function iterates through the array one by one, at each step adding the current array value to the result from the previous step. in our case will compare the previous largest element to the current. the return value will be the object containing the largest value for the age key.
const arr = [
{name: 'John', age: 15},
{name: 'Max', age: 17},
{name: 'Tom', age: 11},
]
const largest = arr.reduce((prev, current) => (prev.age > current.age) ? prev : current)
console.log(largest);
I have a js variable like:
var mylist = [[ {item: 'emp', pos:1}, {age: 21, name: 'AA'},
{age: 22, name: 'BB'}, ], ... ];
in my js script, I read
var out = (mylist[0].map(function(i, j){return i.age}))
total = out.length // this has 3 --> ['', '21', '22']
How do I filter out elements in the list and just return the ones with age keyword, so my
total would be = ['21', '22']
I am new to js, so not sure how to handle the ?lambda? function to add a condition or filter out/ return "clean" data.
You can use filter() after map() to remove those undefined values.
var mylist = [[ {item: 'emp', pos:1}, {age: 21, name: 'AA'}, {age: 22, name: 'BB'}]];
var out = mylist[0].map(i => i.age).filter(age => age);
console.log(out);
I have a javascript object as follows.
{
name: "tom",
age: 5,
fruits: [
{name: "apple",qty: 4},
{name: "orange",qty: 13},
{name: "banana",qty: 3}
]
}
I am trying to convert this object into an object given below.
{
name: "tom",
age: 5,
apple: 4,
orange: 13,
banana: 3
}
How do I achieve this? I have tried to loop through the fruits array but I am unable to find a way to create a variable with the fruit name and assign the qty to it.
You can use forEach and delete to clean up the old key. Take care not to overwrite keys accidentally, though (you could test if (e.name in obj) as a safety check).
const obj = {
name: "tom",
age: 5,
fruits: [
{name: "apple",qty: 4},
{name: "orange",qty: 13},
{name: "banana",qty: 3}
]
};
obj.fruits.forEach(e => obj[e.name] = e.qty);
delete obj.fruits;
console.log(obj);
you can use below simple code
var b={
name: "tom",
age: 5}
for (var i = 0; i<a.fruits.length; i++) {
b[a.fruits[i].name]=a.fruits[i].qty;
}
This a generic function to convert if you don't want to mutate the original object. Destructure the object to get fruits and rest of the properties separately. Then you can use Object.assign() and map to to create a new object.
let obj = {
name: "tom",
age: 5,
fruits: [
{name: "apple",qty: 4},
{name: "orange",qty: 13},
{name: "banana",qty: 3}
]
}
const converter = ({ fruits, ...rest }) =>
Object.assign(rest, ...fruits.map(({ name, qty }) => ({ [name]: qty })))
console.log(converter(obj))
I have an array of objects and trying to take thevalues inside those objects and push them into an array based on the same property value. So for example.
array = [
{name: 'John', age: 12},
{name: 'Lily', age: 22}
]
I have this array of objects and now I want to iterate through it and create arrays with all name values and age values. The array also needs to be the same name as the values. So the result will be.
name = ['John', 'Lily']
age = [12, 22]
How would I be able to do this?
Just map over the array like so:
const array = [
{name: 'John', age: 12},
{name: 'Lily', age: 22}
]
const name = array.map(e => e.name);
const age = array.map(e => e.age);
console.log(name);
console.log(age);
EDIT
If the array has dynamic objects, you can do this:
const array = [
{name: 'John', age: 12},
{name: 'Lily', age: 22}
];
for (var key in array[0]) {
window[key] = array.map(e => e[key]);
}
console.log(name);
console.log(age);
I have a nested array like this
const names= [[{name: "John"}, {name: "Mary"}],
[{name: "Paul"}, {name: "Peter"}]];
I would like inject country into the nested object
const country = {country :"USA"}
so that output looks like
[{name: "John", country : "USA"}, {etc} ,{etc} ]
The code idea have is something like this
const combined = names.map((map)=>
Object.assign({},
country,
/*something to extract name from nested array names*/),
{country}
)
Any suggestions how i could spread the object in the nested array to form the desired output?
If the code could be improved in other ways, please let me know as well
You can use flat() to create a new array with all sub-array elements concatenated before using map() like the following way:
const names= [[{name: "John"}, {name: "Mary"}],
[{name: "Paul"}, {name: "Peter"}]];
const country = {country :"USA"}
const combined = names.flat().map(p => Object.assign(p, country));
console.log(combined);
Make use of reduce to flatten your array along with map and object.assign to add the country value to each object
const names= [[{name: "John"}, {name: "Mary"}],
[{name: "Paul"}, {name: "Peter"}]];
const country = {country :"USA"};
const newNames = names.reduce((acc, item) =>{
acc= acc.concat(item.map(value => Object.assign({}, value, country)));
return acc;
},[]);
console.log(newNames);
It's about using a nested map in an outer map:
const names = [
[{
name: "John"
}, {
name: "Mary"
}],
[{
name: "Paul"
}, {
name: "Peter"
}]
]
const country = { country: 'USA' }
const output = names.map (xs => xs.map (x => ({ ...x, ...country })))
console.log (output)
You might declare a new array literal, list country as the first item, then spread the names[0] array into it, no need for Object.assign nor .map if you only have one sub-array:
const names= [[{name: "John"}, {name: "Mary"}],
[{name: "Paul"}, {name: "Peter"}]];
const country = {country :"USA"};
const newNames = [[country, ...names[0]]];
console.log(newNames);
You can double map the names array and it's nested array and destructure country into each item.
const names = [[{name: "John"}, {name: "Mary"}],
[{name: "Paul"}, {name: "Peter"}]];
const country = {country :"USA"};
const namesWithCountry = names.map(name => name.map(n => ({...n, ...country})));
console.log(namesWithCountry);
You can use .flatMap() to flatten the arrays returned by the inner .map() method:
const names= [[{name: "John"}, {name: "Mary"}], [{name: "Paul"}, {name: "Peter"}]],
res = names.flatMap(arr => arr.map(elem => ({...elem, country: 'USA'})));
console.log(res);