Lazy computed properties in Immutable.js Records? - javascript

Is there a standard way to define lazy computed properties on Records? When I access the computed property, it should run a function to compute the value, then cache the value. For example, something like:
const UserRecord = Record({
firstName: '',
lastName: '',
get fullName() {
console.log('Ran computation');
return `${this.firstName} ${this.lastName}`;
},
});
const user = new UserRecord({ firstName: 'Mark', lastName: 'Zuck' });
console.log(user.fullName); // Ran computation\nMark Zuck
console.log(user.fullName); // Mark Zuck
The closest I can get is defining a getFullName() method, then manually memoizing the computed value. I.e.:
getFullName() {
if (!this._fullName) {
this._fullName = `${this.firstName} ${this.lastName}`;
}
return this._fullName;
}

As long as you don't need it to ever "re-compute" this should do it I think.
const UserRecord = Record({
firstName: '',
lastName: '',
get fullName() {
console.log('Ran computation');
var value = `${this.firstName} ${this.lastName}`;
delete this.fullName;
Object.defineProperty(this, 'fullName', {
value: value
});
return value;
},
});
const user = new UserRecord({ firstName: 'Mark', lastName: 'Zuck' });
console.log(user.fullName); // Ran computation\nMark Zuck
console.log(user.fullName); // Mark Zuck

Related

why can't i assign one object's property to another property?

what could i do to assign the value of firstName's property to lastName's?
const user = {
firstName: "Someone",
lastName: this.firstName,
};
console.log(user.lastName);
// outputs undefined
Using a getter:
const user = {
firstName: "Someone",
get lastName() { return this.firstName; }
};
console.log(user.lastName);

how can i get age from this keyword?

const meDetails = {
firstName: 'arman',
lastName: 'soltani',
birthday: 1991,
hasDriverLicense: true,
calcAge: function () {
this.age = 2037 - this.birthday;
return this.age;
}
};
console.log(meDetails.age);
why the age is not defined??
the variable of named 'age' is not initialized before calling calcAge.
at first you should call calcAge to init meDetailes.age variable at runtime
then meDetails.age is valued and you can use it
You need to call calcAge() first to set the age property
meDetails.calcAge();
console.log(meDetails.age);
But you probably want a getter for age.
const meDetails = {
firstName: 'arman',
lastName: 'soltani',
birthday: 1991,
hasDriverLicense: true,
get age() {
return 2037 - this.birthday;
}
};
console.log(meDetails.age);

Change a value from a nested object using localstorage

I have this code that set the obj value in localstorage.
const obj = {
name: "Bill",
meta: {
age: 18
}
};
const data = localStorage.setItem('user', JSON.stringify(obj));
Now i want to change the age key in the localstorage:
localStorage.setItem('user', JSON.stringify({ ...data, ...data.meta.age= 15 } }));, but it does not work.
How to change the value above and to see the changes in localstorage?
Assuming you have data, the problem is that ...data.meta.age = 15 is a syntax error. You don't use = in object literals, and it does't make sense to try to spread the age property (which is a number). Instead:
const newData = {
...data,
meta: {
...data.meta,
age: 15,
},
};
localStorage.setItem("user", JSON.stringify(newData));
Notice how we have to create a new outermost object and also a new object for meta.
Live Example:
const data = {
name: "Bill",
meta: {
occupation: "Programmer", // Added so we see it get copied
age: 18,
},
};
const newData = {
...data,
meta: {
...data.meta,
age: 15,
},
};
console.log(newData);

Shorthand for picking object properties - combine ES6 `Object Deconstruction` with `Object Property Value` shorthand

Following code outputs {name: "Bob", surname: "Smith"} and it works fine. I want to know can I make it shorter.
((person = { name: 'Bob', surname: 'Smith', age: 22, }) => {
const {
name, // (a) create variable from deconstructing
surname,
} = person;
return {
name, // (b) reuse variable as new object parameter name (and value)
surname
}
})();
Can I somehow merge object deconstruction to variables (a) with returning a new object with Object Property Value shorthand (b)?
I use here shorthand but then its purpose is defeated by the need to manually re-use parameters. I want to mention the name or surname word in my function once not twice...
Destructure person in the function's declaration:
const result = (({ name, surname } = { name: 'Bob', surname: 'Smith', age: 22, }) => ({
name, // (b) reuse variable as new object parameter name (and value)
surname
}))();
console.log(result);
You can not mention it at all
((person = { name: 'Bob', surname: 'Smith', age: 22, }) => {
const {age,...ans} = person;
return ans
})()

How to get specific value from JSON

I have JSON, which looks like this:
{ '-KiJz4D0pGYE35HPP-E4': { code: '211', lastname: 'Smith', firstname: 'John' } }
I do know that it will always look this way, ONLY one child in any case. How could I get value '211' stored under code key. Right now I have ugly code with foreach, it even works, but... Why would I use foreach at all if I know there is only one child?
Thanks a lot!
DEMO
var jsonObj = {
'-KiJz4D0pGYE35HPP-E4': {
code: '211',
lastname: 'Smith',
firstname: 'John'
}
};
var objKey = Object.keys(jsonObj); // return the object key
var innerObject = jsonObj[objKey]; // return the inner object
var code = innerObject.code; // return the code property value.
console.log(code);
USe Object.keys(obj)[0] to get the first key and then you can get the key code's value from it like
var obj = { '-KiJz4D0pGYE35HPP-E4': { code: '211', lastname: 'Smith', firstname: 'John' } }
console.log(obj[Object.keys(obj)[0]]['code']);
If
var data = { '-KiJz4D0pGYE35HPP-E4': { code: '211', lastname: 'Smith', firstname: 'John' } };
Then
data[Object.keys(data)[0]] will return your inner object
{ code: '211', lastname: 'Smith', firstname: 'John' }
So you easily get code value by data[Object.keys(data)[0]].code
Object.values({ '-KiJz4D0pGYE35HPP-E4': { code: '211', lastname: 'Smith', firstname: 'John' } })[0].code;
Simply get the first value of the outer Object...

Categories