I need to take an array objects that and map it so that the new array is just a simple array if each object's id.
So for example:
[
{id: 49, name: "Rest update test"},
{id: 12, name: "Rest test"}
]
would become:
[49, 12]
i have tried this so far:
myObject.map(object => object.id);
so my actual function that is not working is the following, when I view the console.log, it is showing the original object:
onSubmit() {
this.userForm.value.accountsToAdd.map(object => object.id);
console.log(this.userForm.value.accountsToAdd);
}
Assuming the given code does not work, then you need to assign the result of mapping.
Array#map does not mutate the original array but return a new one.
var array = [{ id: 49, name: "Rest update test" }, { id: 12, name: "Rest test" }],
ids = array.map(object => object.id);
console.log(ids);
Related
Hi I would like to map over an array and sort it depending on an lookup object.
const obj = {
"email": {position: 1, name: "email"},
"firstname": {position: 2, name: "firstname"},
"lastname": {position: 3, name: "lastname"}
}
const arr = ["lastname", "email", "firstname"];
expected output: ["email", "firstname", "lastname"];
I know that I must use the map function in order to return a new array.
I can get an new array with the full or object or retrieving only a array with all names or position properties.
But I cannot figure out how to sort them.
Thanks for your help
Array.sort function accepts a callback (sorter) function that will return comparison of any two items in array. So just need to compare their position (of 2 items in array). This is done by substracting them to get a positive/0/negative result.
const obj = {
"email": {position: 1, name: "email"},
"firstname": {position: 2, name: "firstname"},
"lastname": {position: 3, name: "lastname"}
}
const arr = ["lastname", "email", "firstname"];
// expected output: ["email", "firstname", "lastname"];
arr.sort(function(a,b) {
return obj[a].position - obj[b].position
})
console.log(arr)
i'm pretty beginner in the JavaScript and I really need help to convert an array to an array object. There are many examples here in stackOverflow, but I need some modidfication during this process, which is why I couldn't do anything
For example I have:
data = [{id: 21, name: "jack"} , {id: 185, name: "yas"}]
and I need to convert it with something like that (id key change to student_id, and present = true, should be added), and the length of this array is dynamic and will change over time.
[
{
"student_id" : 21,
"present" = true
},
{
"student_id" : 185,
"present" = true
}
]
I need to add these array object to:
const data: any = {
here....
};
your help will be much appreciated.
Assuming your data actually looks more like this
data = [{id: 21, name: "jack"}, {id: 185, name: "yas"}]
This is a simple matter of mapping the array to a new format with the properties you want
const data = [{id: 21, name: "jack"}, {id: 185, name: "yas"}]
const newData = data.map(({ id }) => ({
student_id: id,
present: true
}))
console.log(newData)
So i need to write a function which updates my object with another object (but this object is inside an array) , for example:
const mazda = { model: 5, seria: 22, wheels: 4,};
and i want to add data from :
const newItems= [{ LCDscreen: true },{ wheels: 5 },{ model: 6},{ weight: 500},{ mirrors: 4},];
but so the seria from 1st object is unchanged. The result should be
{ seria: 22 ,model: 6, wheels: 4, LCDscreen: true, weight: 500 , mirrors: 4};
Whats the best approach?
You can simple loop through the array and spread the array objects inside the mazda object. This is the fastest method after using a for loop.
let mazda = { model: 5, seria: 22, wheels: 4,};
const newItems= [{ LCDscreen: true },{ wheels: 5 },{ model: 6},{ weight: 500},{ mirrors: 4}]
newItems.forEach(item => {
mazda = {...mazda, ...item};
});
console.log(mazda)
This can be done in a single line:
newItems.reduce((acc, patch) => Object.assign(acc, patch), mazda)
This iterates over all objects in the newItems list and merges them into mazda one after one.
If you don't want the mazda object to be modified but instead get a new object, use an empty object ({}) as first parameter to Object.assign:
const newMazda = newItems.reduce((acc, patch) => Object.assign({}, acc, patch), mazda)
I think this does what you want it to. Take each item in the newList and add it as a new property to the mazda object.
const mazda = { model: 5, seria: 22, wheels: 4,};
const newItems= [{ LCDscreen: true },{ wheels: 5 },{ model: 6},{ weight: 500},{ mirrors: 4}]
const result = newItems.reduce( (acc,item) => ({...acc,...item}),mazda);
console.log(result)
I have been trying to resolve an issue where my conditional logic doesn't work when I have the same string value in two elements of an array. I have been trying it with for-loops, but without success.
What occurs to me after thinking about it is that the best way to handle this is to take my three arrays - of which, in my use case, there will ALWAYS be an equal number of elements, and mash them together into a new array of objects -- taking the corresponding value from each array element to popular the new array of objects.
Imagine data like this:
const goalScorers = ['John Smith', 'Dave Jones', 'Rob Porter'];
const goalTimes = [4, 23, 56];
const goalTypes = ['penalty', 'breakaway', 'header'];
How best should I handle this to end up with array like this:
const combinedArr = [
{ scorer: 'John Smith', time: 4, type: 'penalty' },
{ scorer: 'Dave Jones', time: 23, type: 'breakaway' },
{ scorer: 'Rob Porter', time: 56, type: 'header' }
]
Map over one of the arrays. The callback function receives the array index, it can use that to access the corresponding elements of the other arrays.
const combinedArr = goalScorers.map((scorer, i) => ({
scorer: scorer, time: goalTimes[i], type: goalTypes[i]
}));
If all the arrays are sorted correctly, so each index is the same instance in every array than you can parse one with map and use index to populate other fields
const goalScorers = ['John Smith', 'Dave Jones', 'Rob Porter'];
const goalTimes = [4, 23, 56];
const goalTypes = ['penalty', 'breakaway', 'header'];
const newArray = goalScorers.map((element, index) => {
return {
scorer: element,
time: goalTimes[index],
type: goalTypes[index],
}
})
console.log(newArray)
I have an array of objects and an array of primitive values. I want to create a new array of objects that maps the values of the first to the latter.
Here's the array of objects:
var eventInstances = [
{
id: 1,
title: "Item 1"
},
{
id: 2,
title: "Item 2"
},
{
id: 1,
title: "Item 3"
},
{
id: 3,
title: "Item 4"
},
]
And the array of primitive values:
var dates = [1, 2, 3]
I want map the objects of eventInstances to a new Array of objects with the values of dateInstances as keys, which would correspond with the value of id in eventInstances.
The result should be:
var dateInstances = [
{
id: 1,
instances: [
{
title: "Item 1"
},
{
title: "Item 1"
}
]
},
{
id: 2,
instances: [
{
title: "Item 1"
},
{
title: "Item 1"
}
]
},
{
id: 3,
instances: [
{
title: "Item 2"
}
]
}
];
Sorry, if this is a newbie question, I've been reading up on sorting methods, but I'm quite at a loss here. Any hint would be highly appreciated. Thanks!
This function will give you your expected result.
dates.map(id=>{
return {id:id,
instances:eventInstances.filter(item =>{
return item.id === id;
})
.map(foundItem => {
return {title: foundItem.title}
})
}});
Might be a simpler way to do it, but here's what's happening. Use map to iterate through your dates array. Then filter to find items in eventInstances that match, then map through those again to just return the title.
Array.map docs
Array.filter docs
You actually don't need the second array, as all those id can be found in the data.
You could collect the data in a map keyed by id and then extract the values:
const eventInstances = [{id: 1,title: "Item 1"},{id: 2,title: "Item 2"},{id: 1,title: "Item 3"},{id: 3,title: "Item 4"}];
const map = new Map(eventInstances.map(({id}) => [id, {id, instances: []}]));
eventInstances.forEach(({id, title}) => map.get(id).instances.push({ title }));
const result = [...map.values()];
console.log(result);
This creates a Map from the data. The Map is populated using its constructor argument, which can accept an array of pairs as input. Such a pair will serve as key/value pair in the Map being constructed. The pairs that are given to the constructor look like this:
[id, {id, instances: []}]
And so the Map will have its keys set to ids and its values will be objects in the form {id, instances: []}. Duplicate id values will not result in extra entries... they will be ignored in the process.
The next step is the forEach loop, which puts values inside those instances properties.
Finally, the keys of the Map have served their purpose, they can now be ejected. We only need the values, which are turned into an array through the spread syntax.
I think you are looking for an object where the key equals to the id, and the value equals to an array of titles, like:
{
"0":[
"title1",
"title2"
],
"1":[
"title1",
"title2"
],
}
To achieve that you need:
var dateInstances = {};
for(let i =0; i<eventInstances.length;i++){
if (!Array.isArray(dateInstances[eventInstances[i]["id"]])){
dateInstances[eventInstances[i]["id"]] = [];
}
dateInstances[eventInstances[i]["id"]].push(eventInstances[i]["id"]["title"]);
}