I have an empty array inside the object like this,
const account = {
name: "David Reallycool",
expenses: []
}
and I need to create a function to add expense into an empty array, the result I need is,
const account = {
name: "David Reallycool",
expenses: [
{
descrition: "Rent",
amount: 1000
},
{
description: "Coffee",
amount: 2.50
}
]
How can I manipulate it?
const addExpense = (expense) => {
account.expenses.push(expense)
}
// use like this
addExpense({ description: 'Rent', amount: 1000 })
addExpense({ description: 'Coffee', amount: 2.5 })
const account = {
name: "David Reallycool",
expenses: []
}
function addExpense(description, amount){
account.expenses.push({"description": description, "amount":amount});
}
addExpense("Test", 500);
console.log(account);
You need to know two things for that:
Changing value in array reflects the change in the original array if you are passing the array as a function parameter as it is passed by reference.
You need to use push() function of Array prototype to add that object in your expenses array.
function addExpense(expensesArray, expense){
expensesArray.push(expense);
}
const account = {
name: "David Reallycool",
expenses: []
};
var expense = {
descrition: "Rent",
amount: 1000
}
addExpense(account.expenses, expense);
var expense = {
descrition: "Coffee",
amount: 2.5
}
addExpense(account.expenses, expense);
console.log(account);
As an object (account) is transferred not as a copy you can manipulate it without problems inside your function.
function addExpenses(inputAccount){
inputAccount.expenses = [
{
descrition: "Rent",
amount: 1000
},
{
description: "Coffee",
amount: 2.50
}
]
}
// will be called with
addExpenses(account);
// here account will have expenses content
Related
I have 100 objects of data within an array that looks like this:
{
id: "1",
date: "2022/01/01",
name: "John",
},
{
id: "2",
date: "2022/01/02",
name: "Chris",
},
I am trying to return an array of objects by date that also returns the names.
For example:
[
{
date: "2022/01/01",
names: ["John", "Steve"...]
},
{
date: "2022/01/02",
names: ["Chris", "Rob"...]
},
]
I have tried using the reduce method:
const groupedByDate = () =>
data.reduce((itemsIterated, { date, name }) => {
if (!itemsIterated[date]) {
itemsIterated[date] = {
date,
names: [],
};
}
itemsIterated[date].names.push(name);
return itemsIterated;
}, []);
The issue is this gives me array with a key of the date and then the object with date/names but I don't know how to return just the array of objects by date.
The function groupedByDate would return an object like this -
const result = {
'2022/01/01': {
date: "2022/01/01",
names: ["John", "Steve"...]
},
'2022/01/02': {
date: "2022/01/02",
names: ["Chris", "Rob"...]
},
}
However, to retrieve it in the format you need, you would need to make use of Object.values().
Object.values(result);
/*
[
{
date: "2022/01/01",
names: ["John", "Steve"...]
},
{
date: "2022/01/02",
names: ["Chris", "Rob"...]
},
]
*/
NOTE
To learn more about Object.values() - MDN
reduce's second parameter is the initial value of the accumulator. Here, we would need to use {} instead of [] in the groupedByDate function.
Just a bit confused as to why this magic method is returning null. It's probably very simple, but I'm using methods I wouldn't normally (bulkingCreating) and can't currently see it.
Association: Country.hasOne(Capital, { foreignKey: 'countryId' });
Populating dummy data:
const countries = await Country.bulkCreate([
{ name: 'England' },
{ name: 'Spain' },
{ name: 'France' },
{ name: 'Canada' }
]);
const capitals = await Capital.bulkCreate([
{ name: 'London' },
{ name: 'Madrid'},
{ name: 'Paris' },
{ name: 'Ottawa' }
]);
countries.forEach((country, index) => {
country.setCapital(capitals[index]);
});
const country = await Country.findOne({where: {name: 'Spain'}});
console.log(country.name, Object.keys(country.__proto__)); // Spain / magic methods
const capital = await country.getCapital();
console.log(capital); // null
The table:
Am I wrong in thinking country.getCapital() should return the relevant entry?
As you might guess setCapital should be an async function because it makes changes in DB so you need to use for instead of forEach method that does not support async callbacks:
let index = 0;
for (const country of countries) {
await country.setCapital(capitals[index]);
index += 1;
}
It would be better to create countries one by one and create capitals for them not relying on the same indexes of both collections (DB might return created records in a different order).
If you are using Sequelize 5.14+, you can do this in 1 bulkCreate using include option.
const countries = await Country.bulkCreate([
{
name: 'England',
Capital: { // This keyname should be matching with model name.
name: 'London'
}
},
{
name: 'Spain',
Capital: {
name: 'Madrid'
}
},
...
],
{
include: Capital,
returning: true // If Postgres, add this if you want the created object to be returned.
}
);
[Noob to Javascript and React] I am using an API that returns an object with values like this. AAPL, AMZN, FB, GOOGL, can be anything based on the function's string array input.
{
AAPL: { price: 329.99 },
AMZN: { price: 2563.05 },
FB: { price: 239.93 },
GOOGL: { price: 1469.12 }
}
How could I consider dynamically mapping a response like this into a state object like this? The id property doesn't exist, it needs to be created.
state = {
stocks: [ { id: 1, name: 'AAPL', price: 329.99 }, { id: 2, name: 'AMZN', price: 2563.05 }, ...]
}
I'm able to successfully print the stock names and their prices separately but I am having trouble figuring out how I could wire them into a state object like what's above.
function getCurrentPriceOfBatchStocks(_stocks) {
iex
.symbols(_stocks)
.price()
.then(res => {
console.log(typeof res);
console.log(res);
console.log(Object.keys(res));
console.log(Object.values(res));
});
}
Not sure where you're getting id from, so I'm using idx as an example.
const stocks = Object.keys(resp).map((key, idx) => ({ id: idx + 1, name: key, price: resp[key] }))
Here is an implementation. With Object.entries, you get an array with an array of [key, value] of your original object. And you can map this array to a different format.
You can check the result with the Run code snippet button.
let st = {
AAPL: { price: 329.99 },
AMZN: { price: 2563.05 },
FB: { price: 239.93 },
GOOGL: { price: 1469.12 }
}
let stocks = Object.entries(st).map(([key, value], index) => ({id: index + 1, name: key, price: value.price}))
console.log(stocks)
const res={
AAPL: { price: 329.99 },
AMZN: { price: 2563.05 },
FB: { price: 239.93 },
GOOGL: { price: 1469.12 }
}
console.log(Object.entries(res).map((entry,index)=>{
return {
id:index+1,
name:entry[0],
...entry[1]
}
}));
I am trying to create a new object based off an existing array. I want to create a new object that show below
{ jack: 'jack', content: 'ocean'},
{ marie: 'marie', content: 'pond'},
{ james: 'james', content: 'fish biscuit'},
{paul: 'paul', content: 'cake'}
const words = ['jack','marie','james','paul']
const myUsers = [
{ name: 'jack', likes: 'ocean' },
{ name: 'marie', likes: 'pond' },
{ name: 'james', likes: 'fish biscuits' },
{ name: 'paul', likes: 'cake' }
]
const usersByLikes = words.map(word => {
const container = {};
container[word] = myUsers.map(user => user.name);
container.content = myUsers[0].likes;
return container;
})
I am not getting the correct object, but instead it returns a list.
[ { jack: [ 'shark', 'turtle', 'otter' ], content: 'ocean'}, { marie: [ 'shark', 'turtle', 'otter' ], content: 'ocean' },
{ james: [ 'shark', 'turtle', 'otter' ], content: 'ocean' },
{ paul: [ 'shark', 'turtle', 'otter' ], content: 'ocean'} ]
What is the role of words array? I think the below code will work.
const result = myUsers.map(user => ({
[user.name]: user.name,
content: user.likes
}));
console.log('result', result);
In case, if want to filter the users in word array then below solution will work for you.
const result = myUsers.filter(user => {
if (words.includes(user.name)) {
return ({
[user.name]: user.name,
content: user.likes
})
}
return false;
});
You can achieve your need with a single loop.
The answer #aravindan-venkatesan gave should give you the result you are looking for. However important to consider:
When using .map() javascript returns an array of the same length, with whatever transformations you told it to inside map().
If you want to create a brand new object, of your own construction. Try using .reduce(). This allows you to set an input variable, i.e: object, array or string.
Then loop over, and return exactly what you want, not a mapped version of the old array.
See here for more details:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
I have an array that contains nested objects, and i want to filter the objects according to a particular field. Items array contains an item object, that contains some particular field like name, id, price, and vendorid. I want to sort and filter the array according to the vendorid field. For example an array like :
var items=[{item:{name:"cap",
id:"5d767e1358ad1d0ca4894592",
price:50,
vendorid:"5d72d2a6d87c4628ba60e046"
},
}
{item:{name:"shorts",
price:100,
vendorid:"5d71c51f2092d318a1bf8f53"
}
},
{item:{name:"shoes",
price:90,
vendorid:"5d71c51f2092d318a1bf8f53"
}
}
{item:{name:"black hood",
price:120,
vendorid:"5d71c51f2092d318a1bf8f53"
}
}
]
I want to create an object that outputs this :
results = {"5d71c51f2092d318a1bf8f53":[{name:"shorts"
price:100,
vendorid:"5d71c51f2092d318a1bf8f53"},
{name:"shoes",
price:90,
vendorid:"5d71c51f2092d318a1bf8f53"},
{name:"black hood",
price:120,
vendorid:"5d71c51f2092d318a1bf8f53"}
],
"5d72d2a6d87c4628ba60e046":[{name:"cap",
id:"5d767e1358ad1d0ca4894592",
price:50,
vendorid:"5d72d2a6d87c4628ba60e046"
}
]
}
The results object format is {vendorid:[array containing objects with the same vendorid]}.
Thanks very much!!!
You can use reduce() method to do that.
var items = [{ item: { name: "cap", id: "5d767e1358ad1d0ca4894592", price: 50, vendorid: "5d72d2a6d87c4628ba60e046" } } ,{ item: { name: "shorts", price: 100, vendorid: "5d71c51f2092d318a1bf8f53" } }, { item: { name: "shoes", price: 90, vendorid: "5d71c51f2092d318a1bf8f53" } }, { item: { name: "black hood", price: 120, vendorid: "5d71c51f2092d318a1bf8f53" } } ];
let result = items.reduce((obj, currentValue) => {
if (!obj[currentValue.item.vendorid]) {
obj[currentValue.item.vendorid] = [];
}
obj[currentValue.item.vendorid].push({
...currentValue.item
});
return obj;
}, {});
const orderedResult = {};
// Sorting on vendorid.
Object.keys(result).sort().forEach(key => orderedResult[key] = result[key]);
console.log(orderedResult);
A note on ordering of object properties:
As of ECMAScript 2015 (ES6), object's own properties do have order
for some operations, but relying on it isn't a good idea. If order is
important, then better to use an array or something similar.