How can I push an object into an array?
You have to create an object. Assign the values to the object. Then push it into the array:
var nietos = [];
var obj = {};
obj["01"] = nieto.label;
obj["02"] = nieto.value;
nietos.push(obj);
Adding an object conditionally inside an array
From what I understood, you want to filter away all the elements of the array given a condition. What I would do is adding a new key to the object specifying if it should be displayed, and then filter & map.
const typesOfCards = [
{ name: "Card A", size: "Medium", action: "make", type: "typeA" },
...
];
return typesOfCards.filter(card => card.type === "typeA").map(({ name, size, action }) => (
<BuildCard name={name} size={size} action={action} />
));
Add key value pair to all objects in array
The map() function is a best choice for this case
tl;dr - Do this:
const newArr = [
{name: 'eve'},
{name: 'john'},
{name: 'jane'}
].map(v => ({...v, isActive: true}))
The map() function won't modify the initial array, but creates a new one.
This is also a good practice to keep initial array unmodified.
Alternatives:
const initialArr = [
{name: 'eve'},
{name: 'john'},
{name: 'jane'}
]
const newArr1 = initialArr.map(v => ({...v, isActive: true}))
const newArr2 = initialArr.map(v => Object.assign(v, {isActive: true}))
// Results of newArr1 and newArr2 are the same
Add a key value pair conditionally
const arr = [{value: 1}, {value: 1}, {value: 2}]
const newArr1 = arr.map(v => ({...v, isActive: v.value > 1}))
What if I don't want to add new field at all if the condition is false?
const arr = [{value: 1}, {value: 1}, {value: 2}]
const newArr = arr.map(v => {
return v.value > 1 ? {...v, isActive: true} : v
})
Adding WITH modification of the initial array
const initialArr = [{a: 1}, {b: 2}]
initialArr.forEach(v => {v.isActive = true;});
This is probably not a best idea, but in a real life sometimes it's the only way.
Questions
- Should I use a spread operator(
...
), orObject.assign
and what's the difference?
Personally I prefer to use spread operator, because I think it uses much wider in modern web community (especially react's developers love it). But you can check the difference yourself: link(a bit opinionated and old, but still)
- Can I use
function
keyword instead of=>
?
Sure you can. The fat arrow (=>
) functions play a bit different with this
, but it's not so important for this particular case. But fat arrows function shorter and sometimes plays better as a callbacks. Therefore the usage of fat arrow functions is more modern approach.
- What Actually happens inside map function:
.map(v => ({...v, isActive: true})
?
Map function iterates by array's elements and apply callback function for each of them. That callback function should return something that will become an element of a new array.
We tell to the .map()
function following: take current value(v
which is an object), take all key-value pairs away from v
andput it inside a new object({...v}
), but also add property isActive
and set it to true ({...v, isActive: true}
) and then return the result. Btw, if original object contains isActive
filed it will be overwritten. Object.assign
works in a similar way.
- Can I add more then one field at a time
Yes.
[{value: 1}, {value: 1}, {value: 2}].map(v => ({...v, isActive: true, howAreYou: 'good'}))
- What I should not do inside
.map()
method
You shouldn't do any side effects[link 1, link 2], but apparently you can.
Also be noticed that map()
iterates over each element of the array and apply function for each of them. So if you do some heavy stuff inside, you might be slow. This (a bit hacky) solution might be more productive in some cases (but I don't think you should apply it more then once in a lifetime).
- Can I extract map's callback to a separate function?
Sure you can.
const arr = [{value: 1}, {value: 1}, {value: 2}]
const newArr = arr.map(addIsActive)
function addIsActive(v) {
return {...v, isActive: true}
}
- What's wrong with old good for loop?
Nothing is wrong with for
, you can still use it, it's just an old-school approach which is more verbose, less safe and mutate the initial array. But you can try:
const arr = [{a: 1}, {b: 2}]
for (let i = 0; i < arr.length; i++) {
arr[i].isActive = true
}
- What also i should learn
It would be smart to learn well following methods map(), filter(), reduce(), forEach(), and find(). These methods can solve 80% of what you usually want to do with arrays.
How to insert an item into an array at a specific index (JavaScript)
You want the splice
function on the native array object.
arr.splice(index, 0, item);
will insert item
into arr
at the specified index
(deleting 0
items first, that is, it's just an insert).
In this example we will create an array and add an element to it into index 2:
var arr = [];
arr[0] = "Jani";
arr[1] = "Hege";
arr[2] = "Stale";
arr[3] = "Kai Jim";
arr[4] = "Borge";
console.log(arr.join()); // Jani,Hege,Stale,Kai Jim,Borge
arr.splice(2, 0, "Lene");
console.log(arr.join()); // Jani,Hege,Lene,Stale,Kai Jim,Borge
Add property to an array of objects
You can use the forEach
method to execute a provided function once for each element in the array. In this provided function you can add the Active
property to the element.
Results.forEach(function (element) {
element.Active = "false";
});
In PHP, how can I add an object element to an array?
Just do:
$object = new stdClass();
$object->name = "My name";
$myArray[] = $object;
You need to create the object first (the new
line) and then push it onto the end of the array (the []
line).
You can also do this:
$myArray[] = (object) ['name' => 'My name'];
However I would argue that's not as readable, even if it is more succinct.
Javascript - adding objects to array with matching id
Here's one way to get there using your code but filtering matching articles and using the spread
operator
let combined = categories.results.map(item => ({ ...item,
articles: articles.filter(f => f.categoryId == item.id)
}));
const articles = [{
"title": "first article",
"content": "lorem ipsum",
"categoryId": 28
},
{
"title": "second article",
"content": "lorem ipsum",
"categoryId": 28
},
{
"title": "thirdarticle",
"content": "lorem ipsum",
"categoryId": 76
},
]
const categories = {
results: [{
"id": 28,
"name": "Articles"
}, {
"id": 76,
"name": "Projects"
}]
}
let combined = categories.results.map(item => ({ ...item,
articles: articles.filter(f => f.categoryId == item.id)
}));
console.log(combined)
How to add an object to an array based on its values?
Please see the below solution with an O(N)
time complexity.
It was made with an assumption that the desired insertion index logic is (user.Speed1 * user.Speed2) < (newUser.Speed1 * newUser.Speed2)
. Consequently, among all users with identical speeds, the new user will be inserted as the last one.
Noteworthy, though, the users
may be not-the-best data structure for this task.
const users = [
{ Rank: 1, Speed1: 91, Speed2: 457, Username: 'monizotic', ProfileLink: 'profile_link', VerifiedSpeed: null, Video: null },
{ Rank: 2, Speed1: 91, Speed2: 457, Username: 'Thachtawan', ProfileLink: 'profile_link', VerifiedSpeed: null, Video: null },
{ Rank: 3, Speed1: 91, Speed2: 456, Username: 'PassornSibpang', ProfileLink: 'profile_link', VerifiedSpeed: null, Video: null },
{ Rank: 4, Speed1: 91, Speed2: 456, Username: 'WasinSoikeeree', ProfileLink: 'profile_link', VerifiedSpeed: null, Video: null },
{ Rank: 5, Speed1: 91, Speed2: 454, Username: 'user1055644', ProfileLink: 'profile_link', VerifiedSpeed: null, Video: null }
];
const insertUser = newUser => {
const newUserSpeed = newUser.Speed1 * newUser.Speed2;
let insertIndex = users.findIndex(user => (user.Speed1 * user.Speed2) < newUserSpeed);
insertIndex = insertIndex >= 0 ? insertIndex : users.length;
// assign the new user a rank
newUser.Rank = insertIndex + 1;
// insert the user
users.splice(insertIndex, 0, newUser);
// increment ranks of subsequent users
users.slice(insertIndex + 1).forEach(user => user.Rank++);
};
insertUser({ Rank: null, Speed1: 91, Speed2: 456, Username: 'thaniman', ProfileLink: 'profile_link', VerifiedSpeed: null, Video: null });
console.log(JSON.stringify(users))
Add same object to an array
You can try this code:
class Fruits {
constructor() {
this.items = [];
this.totals = 0;
}
calculateTotals() {
this.totals = 0;
this.items.forEach(item => {
let price = item.price;
let quantity = item.quantity;
let amount = price * quantity;
this.totals += amount;
});
}
addToCart(fruit, price, quantity) {
let obj = { fruit, price, quantity }
this.items.push(obj);
this.calculateTotals();
}
get cart() {
return { items: this.items, totals: this.totals }
}
}
const fruitsCart = new Fruits();
fruitsCart.addToCart("Apple", 10.5, 2);
fruitsCart.addToCart("Orang", 15, 1);
const cart = fruitsCart.cart;
Related Topics
Remove All White Spaces from Text
What's the Purpose of Prototype
Jquery to Loop Through Elements with the Same Class
How to Set Multiple CSS Styles in JavaScript
Get the Index of the Object Inside an Array, Matching a Condition
How to Copy Static Files to Build Directory with Webpack
Getting Unexpected Token Export
Equivalent of String.Format in Jquery
Understanding Meteor Publish/Subscribe
How to Capitalize First Letter of Each Word, Like a 2-Word City
Is Node.Js Native Promise.All Processing in Parallel or Sequentially
Parse JSON String into a Particular Object Prototype in JavaScript
Get Protocol, Domain, and Port from Url
What Does $(Function() {} ); Do
Pass Parameters in Setinterval Function