Object.assign() and array of objects - javascript

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

Related

Adding new keys and a set of values to an already existing array in javascript

I have this data:
myArray=['joe', 'sarah', 'jack', 'steph']
tempString = ' rogan'
I want to convert it to this:
myArray=[
{name: 'joe', value: 'joe rogan'},
{name: 'sarah', value: 'sarah rogan'},
{name: 'jack', value: 'jack rogan'},
{name: 'steph', value: 'steph rogan'}
]
I have tried:
myArray.map(o => ({ name: o.name }, { value: o.name + tempString });
but it doesn't work. How can I do it?
You want to return one object with both properties, so you should not be creating two separate object literals. In your case, the comma operator is causing only the last (second) one to be returned.
const myArray=['joe', 'sarah', 'jack', 'steph']
const tempString = ' rogan'
const res = myArray.map((name)=>({name,value:name+tempString}));
console.log(res);
Below snippet could help you
const myArray = ["joe", "sarah", "jack", "steph"]
const tempString = " rogan"
const res = myArray.map((name) => ({
name: name,
value: name + tempString,
}))
console.log(res)
You can also use the forEach function to iterate through arrays:
const myArray = ["joe", "sarah", "jack", "steph"]
const tempString = " rogan";
let newArray = [];
myArray.forEach((name) => newArray.push({name, value: name + tempString}));
console.log(newArray);

Two array of object merge in another array object

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

Extract data from an array and include it to an object in javascript

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

How to take an array of objects and create arrays based on property values?

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

Search for all values in array of objects

I have three arrays.
One of them contains values I will be testing. The two others are arrays of object which might include the values of my first array under the name key.
const myArray = ["foo", "bar"];
const testArray1 = [
{name: "foo"},
{name: "bar"},
{name: "something else"}
]
const testArray2 = [
{name: "foo"},
{name: "rab"},
{name: "something else"}
]
I am trying to write a condition which would return true only if the tested array contains all of the values of my first array.
With the same example it would give me something like this :
if (testArray1.containsAll(myArray)) // true
if (testArray2.containsAll(myArray)) // false
What is the best way to resolve this ?
Thanks, any help much appreciated
With array.prototype.every and array.prototype.find, it should be:
const myArray = ["foo", "bar"];
const testArray1 = [
{name: "foo"},
{name: "bar"},
{name: "something else"}
];
const testArray2 = [
{name: "foo"},
{name: "rab"},
{name: "something"}
];
console.log(myArray.every(s => testArray1.find(o => o.name === s)));
console.log(myArray.every(s => testArray2.find(o => o.name === s)));
can be use, every and some. these are return only true/false
const myArray = ["foo", "bar"];
const testArray1 = [
{name: "foo"},
{name: "bar"},
{name: "something else"}
]
const testArray2 = [
{name: "foo"},
{name: "rab"},
{name: "something else"}
]
let result1 = testArray1.every(item => myArray.some(array => item.name == array))
let result2 = testArray2.every(item => myArray.some(array => item.name == array))
console.log('result1', result1)
console.log('result2', result2)
Check this out. May not be the best way but works perfectly fine.
const myArray = ["foo", "bar"];
const testArray1 = [
{name: "foo"},
{name: "bar"},
{name: "something else"}
]
const testArray2 = [
{name: "foo"},
{name: "rab"},
{name: "something else"}
]
let aFlag = testArray1.filter( a => myArray.includes(a.name)).length === myArray.length;
let bFlag = testArray2.filter( a => myArray.includes(a.name)).length === myArray.length;
console.log(aFlag, bFlag)

Categories