Store an object inside another object - javascript

I need to insert one object inside another, and I'm using this logic:
// Create object store
const store = {}
// Function to create 'Product' Objects
function createProduct (type, name, price) {
return { type, name, price }
}
// Function to add 'Product' Objects inside the 'Store' Object
function addToStore (obj) {
store.obj = obj
return store
}
const strawberry = createProduct ('fruit', 'strawberry', '0.40')
const peach = createProduct ('fruit', 'peach', '0.80')
addToStore(strawberry)
addToStore(peach)
console.log(store) // < { obj: { type: 'fruit', name: 'peach', price: '0.90' } }
How should I write this function so that store.obj be the same obj passed by parameter?
function addToStore (obj) {
store.obj = obj
return store
// What's happening in the run
function addToStore (peach) {
store.obj = peach
return store
// What I need to happen
function addToStore (peach) {
store.peach = peach
return store

If you mean that you want the property name to come from the name of the variable you use when calling addToStore, you can't quite do that, because when addToStore gets called, it just receives the value of that variable (the reference to the object), it doesn't receive any information about the variable itself.
The simple solution is to pass the name as a second argument:
function addToStore(name, obj) {
store[name] = obj;
return store;
}
// ...
addToStore("peach", peach);
Note the use of [] to make the property name come from the name parameter rather than using . with a literal name.
There is a way to make that a bit more automatic, at the (very small) cost of creating a temporary object, by using shorthand property syntax. Pass an object wrapper around the object you want, where the name of the property comes from the variable name, and have addToStore take the object from that wrapper (or perhaps take all of them, if you pass more than one):
function addToStore(objects) {
Object.assign(store, objects); // Will do the loop and assignments for you
return store;
}
// ...
addToStore({peach});
// ^^^^^^^−−−−−−−−−−− creating the object to pass in using shorthand syntax
You probably wouldn't want to do that in code that's going to do it millions of times in an hour because of the overhead, but short of that I wouldn't worry about it until/unless you ran into a performance problem you tracked down to it.

Related

Object equals another object syntax [duplicate]

This question already has answers here:
Set a default parameter value for a JavaScript function
(29 answers)
Closed 4 months ago.
There is a function in the testing section in the redux docs and I'm trying to figure out what this syntax means.
export function renderWithProviders(
ui,
{
preloadedState = {},
// Automatically create a store instance if no store was passed in
store = setupStore(preloadedState),
...renderOptions
} = {}
) {
function Wrapper({ children }) {
return <Provider store={store}>{children}</Provider>
}
return { store, ...render(ui, { wrapper: Wrapper, ...renderOptions }) }
}
It seems like there's an object being passed as an argument and then it's assigned to nothing? Trying to figure out what the {...properties} = {} syntax means in the function declaration.
Thank you!
It seems like there's an object being passed as an argument and then it's assigned to nothing?
I assume you're referring to the = {} at the end of (and at the start of):
{
preloadedState = {},
// Automatically create a store instance if no store was passed in
store = setupStore(preloadedState),
...renderOptions
} = {}
That's default argument value syntax. To show a simpler example, if I had a paintCar function, and I wanted to default my car to an empty object if none is provided, I could do:
function paintCar(paintColor, car = {}) {
car.color = paintColor;
return car;
}
// this works, even though I didn't provide a car:
const redCar = paintCar('red'); // { color: 'red' }
// ... because JS defaults that argument to "{}"
For any argument, to any function, you can add a = something to make it default to that something. The only requirement is that all the defaults have to come last, so you can't do (say):
function fake(foo=1, bar){
(or technically you can, but when you do fake(someBar) it will get counted as the foo argument, not the bar argument)

Javascript Set:Get Pointless?

I have been experimenting with getters and setters with the following pattern:
var mytab = {
_tab: undefined,
get: function () {
return this._tab;
},
set: function (tab) {
this._tab = tab;
return tab;
}
}
My question is, given you have to access those methods explicitly, ie:
mytab.get();
mytab.set('thistab');
Why bother having get or set at all? Why not call them whatever you like? ie:
var mytab = {
_tab: undefined,
getthetab: function () {
return this._tab;
},
setthetab: function (tab) {
this._tab = tab;
return tab;
}
}
I may have missed some fundamental principle here, but both these objects behave exactly the same.
I assumed having special 'setters' and 'getters' would allow the object to be modified using it's object name, ie:
var a = mytab;
mytab = 'thistab';
Or even:
var a = mytab();
mytab() = 'thistab';
This is what I expected, and what I wanted, however those instructions give errors, namely that mytab() is not a function.
I would appreciate some clarity on what special significance the set and get object methods actually have.
In your first example, you haven't declared getters/setters. You've created an object with two methods called get and set.
To declare getters/setters, you'll have to choose an arbitrary name, and prefix it with get or set, like:
var mytab = {
_tab: undefined,
get tab() {
return this._tab;
},
set tab(tab) {
this._tab = tab;
return tab;
}
}
In this case, they form a so-called accessor property, that has the chosen name:
console.log(mytab.get) //undefined
console.log(mytab.set) //undefined
mytab.tab = 'foo'
console.log(mytab._tab) //foo
mytab._tab = 'bar'
console.log(mytab.tab) //bar
console.log(Object.getOwnPropertyDescriptor(mytab, 'tab')) /*
{
get: function(){...},
set: function(tab){...},
...
}
*/
However, you cannot overload operators or otherwise define a single getter/setter pair for your objects, that would allow you to assign a value or read a value from the object itself.
You can only define getters/setters for the properties on the object.
So,
var a = mytab
or
mytab = a
cannot be intercepted, and doesn't do what you expect (the first assigns the object itself to another variable (a), while the second reassigns the variable mytab with the value of a without even affecting / interacting with the object).
The following use case can illustrate advantage of using getters and setters
var person = {
firstName: "John",
lastName: "Doe",
get fullName() {
return `${this.firstName} ${this.lastName}`;
}
};
console.log(person.fullName);
Using getter we could use get fullName as if it was a property of person without the need of maintaining separate field.

Please what's wrong with this code, it's my homework I keep getting error

The above exercise was created to be completed by my teacher and I keep getting error when I ran it.
function exerciseOne() {
// Exercise One: In this exercise you will create a variable called 'aboutMe'
// This variable should be assigned a new object
// In this object create three key:value pairs
// The keys should be: 'name', 'city', 'favoriteAnimal'
// The values should be strings associated with the keys.
// return the variable 'aboutMe'
let aboutMe = {
name: 'Adebola Adesina',
city: 'Los Angeles',
favoriteAnimal: 'Zebra'
};
return aboutMe;
}
function exerciseTwo(animal) {
// Exercise Two: In this exercise you will be given an object called 'animal'
// Create a new variable called 'animalName'
// Accessing the animal object, assign the 'animalName' variable to the 'latinName' key on the object.
// return the animalName variable.
animalName = animal.latinName;
}
return animalName;
function exerciseThree(userObject) {
// Exercise Three: In this exercise you will be given an object called 'userObject'
// The phonne number for this user is incorrect!
// reassign the 'phoneNumber' key to the value: '(951)867-5309'
// return the userObject
userObject.phoneNumber = '(951)867-5309';
}
return userObject;
The above exercise was created to be completed by my teacher and I keep getting error when I ran it.
function exerciseTwo(animal) {
animalName = animal.latinName;
return animalName;
}
function exerciseThree(userObject) {
userObject.phoneNumber = '(951)867-5309';
return userObject;
}
You have to return the variables inside the function. Read about scope in javascript and differences between var and let. Also, read the error carefully and debug in browser using breakpoints and you will understand where the code is breaking.

Array function type syntex

I was reviewing someones code and he have wrote a syntax which looks like this
export const actions = {
[ACTIONS.SOMEACTION.ATTEMPT.name] ({ commit }, payload) {
return new Promise((resolve, reject) => {
Can someone please explain me what the person is trying to do here? like if someone could explain this syntax?
There are two thing in the code.
Computed Property Names:
[ACTIONS.SOMEACTION.ATTEMPT.name](... this is setting the method for the object whose name will be equal to the value ofACTIONS.SOMEACTION.ATTEMPT.name.
Unpacking fields from objects passed as function parameters
({ commit }, payload)
The line { commit } take out the property commit of the object passed as first parameter to this function.
Eaxample
let str = "func"
let obj = {
[str]({commit},other){
console.log(commit,other);
}
}
obj.func({commit:"the value of commit"},"Other parameter");
This is either inside of an object or a class and declares a method.
[ACTIONS.SOMEACTION.ATTEMPT.name] is a
computed property name, the methods name will be whatever is stored inside ACTIONS.SOMEACTION.ATTEMPT.name.
({ commit }, payload) those are the two parameters the method takes, the first being an object that gets destructured, so the commit property gets taken out of it.
The method then creates and returns a Promise:
return new Promise((resolve, reject) => {
This is using computed property names with destructuring assignment.
Here,
[ACTIONS.SOMEACTION.ATTEMPT.name]
will be converted to the name of the function (due to computer property names). For instance, if ACTIONS.SOMEACTION.ATTEMPT.name was equal to "foo" your result will be somewhat equivlant to:
foo({commit}, payload) {
// ... function body ...
}
which can later be called using .foo(arg1, arg2)
Note: as we are inside an object the function keyword can be omitted.
The {commit} is using destructuring assignment which can be used to "unpack" properties from an object. In this case, commit will be equal to the commit property from arg1. So if you used your function like so:
.foo({commit:10, id:1}, "bar")
Then your function will "unpack" 10 from your first argument object and make that equal to commit.
I am trying to solve.
`let str = "func"
let obj = {
[str]({commit},other){
console.log(commit,other);
}
}
obj.func({commit:"the value of commit"},"Other parameter");`

Passing a new object as parameter to a function changing only 1 value

I have a function that takes an object as parameter. The object has a default value containing many properties and methods which I don't know. I however know one of the properties and I want to pass the default object with the property changed. How do I do it? for eg..
class DataFactory() {
private static getData(data) {} // data is an object having default set properties
}
// Somewhere in my other module
function blabla() {
let name = 'Hello'
let newData = DataFactory.getData(changedObj)
//.... other stuffs
}
// here the changedObj is the default object with only the property called 'name' modified.
changedObj = Object.assign({},changedObj, {name: 'new name'});
Or
changedObj['name'] = 'New Name';

Categories