Array Destructuring + spread syntax with specific field only? - javascript

let arr = [{name: 'john', age:17}, {name: 'Doe', age: 21}];
//let dropDownHumanOptions = ['All', ...arr.name, 'Cancel']
//let dropDownHumanOptions = ['All', ...{arr.name}, 'Cancel']
//Expected: let dropDownHumanOptions = ['All', 'john', 'Doe', 'Cancel']
I'm wondering if there is any similar syntax where we can just extracting one of the field and combine in the middle of another array by using spread syntax?

You need to spread the mapped names.
var array = [{name: 'john', age:17}, {name: 'Doe', age: 21}],
dropDownHumanOptions = ['All', ...array.map(({ name }) => name), 'Cancel'];
console.log(dropDownHumanOptions);

Related

How do I convert an array of objects to an object of objects? [duplicate]

This question already has answers here:
Convert Array to Object
(46 answers)
Closed 26 days ago.
For example, I have the following array of objects:
[{id:1, name: Hana, age: 30}, {id:2, name: Sana, age: 20}, {id:3, name: Kana, age: 30}]
I want to convert it to an object of objects as following:
{0:{id:1, name: Hana, age: 30}, 1:{id:2, name: Sana, age: 20}, 2:{id:3, name: Kana, age: 30}}
Using Object's pre built method assign you can achieve this.
Object.assign({}, yourObject);
No need to iterate through the Array unnecessary.
You can easily achieve the result, using a simple map function and store the result in an object as a key:value pair
const data = [{id:1, name: 'Hana', age: 30}, {id:2, name: 'Sana', age: 20}, {id:3, name: 'Kana', age: 30}]
const resultObj = {}
data.map((obj,index) => resultObj[index] = obj)
console.log(resultObj)
You can map that array and get its unique value (in this case i have taken id as key) then map it according you want to display array.
Here is an example to do that.
var arr = [{
id: 1,
name: 'Hana',
age: 30
}, {
id: 2,
name: 'Sana',
age: 20
}, {
id: 3,
name: 'Kana',
age: 30
}]
var mapped = arr.map(item => ({
[item.id]: item
}));
var newObj = Object.assign({}, ...mapped);
console.log(newObj);

How to remove object if object matches [duplicate]

This question already has answers here:
Object comparison in JavaScript [duplicate]
(10 answers)
Closed 1 year ago.
I am trying to remove object if object matches, I dont want to compare any object key, I just want to compare whole object with array of object, and if it matches, then I have to remove that object from original array.
let originalArray = [
{name: 'abc', country: 'eng'},
{name: 'xyz', country: 'ind'},
{name: 'pqr', country: 'us'}
]
let objectToBeRemove = [
{name: 'pqr', country: 'us'}
]
console.log(originalArray);
Expected output:
[
{name: 'abc', country: 'eng'},
{name: 'xyz', country: 'ind'}
]
I am not able to figure out how can I compare object, I can do it by id or any key, but I am making generic thing, so may be in few cases ID is not present, that's why I want to compare object
One way is to use Array#filter with Array#some + JSON.stringify() for comparison.
Note that Array#filter returns a new array. So the variable needs to be reassigned.
let originalArray = [
{name: 'abc', country: 'eng'},
{name: 'xyz', country: 'ind'},
{name: 'pqr', country: 'us'}
];
let objectToBeRemove = [
{name: 'pqr', country: 'us'}
];
originalArray = originalArray.filter(obj =>
objectToBeRemove.some(objToRemove =>
JSON.stringify(objToRemove) !== JSON.stringify(obj)
)
);
console.log(originalArray);
Note: Using JSON.stringify() is a little primitive for object comparison in my opinion. For instance the check would fail if the properties are in different order {country: 'us', name: 'pqr'}. Better way would be to do a deep comparison. For eg. using _.isEqual from loadash library. See here for more info.
Using loadash
let originalArray = [
{name: 'abc', country: 'eng'},
{name: 'xyz', country: 'ind'},
{name: 'pqr', country: 'us'}
];
let objectToBeRemove = [
{country: 'us', name: 'pqr'}
];
originalArray = originalArray.filter(obj =>
objectToBeRemove.some(objToRemove =>
!_.isEqual(objToRemove, obj)
)
);
console.log(originalArray);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
You can use "filter" function to do that: https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
var myArr = [{name: "toto"}, {name: "tata"}, {name: "tutu"}];
var toRemove = {name: "tata"};
let ret = myArr.filter(function(el) {
return el.name != toRemove.name;
});
Or for removing multiple items:
var myArr = [{name: "toto"}, {name: "tata"}, {name: "tutu"}];
var toRemove = [{name: "tata"}, {name: "tutu"}];
for (var i = 0; i < toRemove.length; i++) {
let index = myArr.findIndex((el) => { // Search item index to remove
return el.name == toRemove[i].name;
});
if (index != -1) myArr.splice(index, 1); // Remove item in found index
}
To compare the equality of the complete object you could use the JSON.stringify() method.
Example;
JSON.stringfy(originalArray[i]) === JSON.stringfy(objectToBeRemove)
try this
let originalArray = [
{ name: 'abc', country: 'eng' },
{ name: 'xyz', country: 'ind' },
{ name: 'pqr', country: 'us' }
];
let objectToBeRemove = [
{ name: 'pqr', country: 'us' }
];
var finalResult = originalArray.filter(function(objFromA) {
return !objectToBeRemove.find(function(objFromB) {
return objFromA.name === objFromB.name
})
});
console.log('???',finalResult);

Return only some keys from an array of objects

I want to display the array but only with name and age
const users = [{name: 'john', age: 20, instrument: 'guitar'}, {name: 'mary', age: 20, instrument: 'piano'}];
let userList = users.map(users => {name: users.name, users.instrument })
console.log(userList);
didn't work. I'm missing a return somewhere right?
You should wrap the object statement in each iteration with ().
Also, I prefer using Destructuring assignment:
const users = [{name: 'john', age: 20, instrument: 'guitar'}, {name: 'mary', age: 20, instrument: 'piano'}];
var new_users = users.map(({name,instrument}) => ({name, instrument}));
console.log(new_users);
You just need to wrap object inside ()
const users = [{name: 'john', age: 20, instrument: 'guitar'}, {name: 'mary', age: 20, instrument: 'piano'}];
var result = users.map(user => ({ name: user.name, instrument: user.instrument }));
console.log(result)
You forgot an = when setting users.
Inside the map function, you called the run-through-object users but use user.
You forgot an ' after 'guitar
You didn't set the key for the instrument value in the mapping function
You need to add brackets () around the object in the mapping function as it will be treated as arrow function if forgotten
In the end it should look like this:
const users = [{name: 'john', age: 20, instrument: 'guitar'}, {name: 'mary', age: 20, instrument: 'piano'}];
const mapped = users.map(user => ({name: user.name, instrument: user.instrument}));
console.log(mapped);

group by Date in Javascript

I have an array of birthdays
const birthdays = [
{name: 'John', birthday: '08-08-1960'},
{name: 'James', birthday: '08-25-1960'},
{name: 'Mary', birthday: '01-01-1990'},
]
and I need to generate a new array with the birthdays grouped by month-year
const grouped = [
{'08-1960': [
{name: 'John', birthday: '08-08-1960'},
{name: 'James', birthday: '08-25-1960'},
]},
{'01-1990': [
{name: 'Mary', birthday: '01-01-1990'},
]},
]
I was looking at something like this. using moment and lodash
let groupedResults = _.groupBy(results, (result) => moment(result['Date'], 'DD/MM/YYYY').startOf('isoWeek'));
but I canĀ“t imagine how to generate the new array structure (with the month-year as keys) thank you.
update: it should return an array not an object :facepalm
You can use reduce()
Apply reduce() on array of object and set accumulator to empty object {}
Then split() birthday by - and get only get first and third element.
If the key exist is accumulator that concat() new value to it. Otherwise concat() it to empty array [] and then set it as property of accumulator.
const arr = [
{name: 'John', birthday: '08-08-1960'},
{name: 'James', birthday: '08-25-1960'},
{name: 'John', birthday: '01-01-1990'},
]
let res = arr.reduce((ac,a) => {
let key = a.birthday.split('-');
key = `${key[0]}-${key[2]}`;
ac[key] = (ac[key] || []).concat(a);
return ac;
},{})
res = Object.entries(res).map(([k,v]) => ({[k]:v}))
console.log(res)
As explained here https://www.dyn-web.com/javascript/arrays/associative.php you can create arrays where the indexes are strings, but i won't work as a normal array.
Here is a snippet for doing what you want.
const birthdays = [
{name: 'John', birthday: '08-08-1960'},
{name: 'James', birthday: '08-25-1960'},
{name: 'Mary', birthday: '01-01-1990'},
];
const grouped = birthdays.reduce((prev, cur) => {
const date = new Date(cur.birthday);
const key = `${(date.getMonth() + 1)}-${date.getFullYear()}`;
if(!prev[key]){
prev[key] = [ cur ];
}
else{
prev[key].push(cur);
}
return prev;
}, []);
for(let i in grouped){
console.log(grouped[i]);
}

How can I keep same object but replace only one property?

Let's say this is my array of objects:
let data = [{
firstname: 'John',
lastname: 'Doe'
},
{
firstname: 'Jane',
lastname: '- Doe'
}]
Now, I want to make a new object, but where - Doe is I need to remove this part - and leave only Doe.
I have tried this:
let pollyData = data.map(item => _.mapValues(item, val => val.lastname.split('- ').pop()))
However, I get undefined.
Is there a better way to achieve this?
Thanks.
Iterate with Array#map. Check if an object includes a lastname with a dash. If so create a new object with a cleaned lastname. If not return the original object.
Note: I've used object spread to replace the lastname. If not supported by your build stack, you can use Object.assign({}, obj, { lastname: obj.lastname.replace(/^-\s+/, '') }) instead.
const data = [{
firstname: 'John',
lastname: 'Doe'
},
{
firstname: 'Jane',
lastname: '- Doe'
}
];
const result = data.map((obj) => obj.lastname.includes('-') ? ({
...obj,
lastname: obj.lastname.replace(/^-\s+/, '')
}) : obj);
console.log(result);
You can use regex and array#map
let data = [{ firstname: 'John', lastname: 'Doe' }, { firstname: 'Jane', lastname: '- Doe' }];
var result = data.map(({firstname, lastname}) =>
({firstname, lastname: lastname.replace(/^\s*\-\s*/g, '')})
);
console.log(result);

Categories

Resources