how to overwrite the existing object using javascript
Just merge the first one by checking id
:
var my_obj = [{ id: "1", logo: "img1.png", name: "fund", speed: "1 Days", targetAmount: "2000" }, { id: "2", logo: "img2.png", name: "transfer", speed: "1 Days", targetAmount: "3000" },]
var merge_obj = { targetAmount: 50688.97, type: "REGULAR"};
var new_obj = my_obj.map(e => { if (e.id == "1") { Object.keys(merge_obj).forEach(key => e[key] = merge_obj[key]); } return e;});console.log(new_obj);
.as-console-wrapper { max-height: 100% !important; top: auto; }
How to replace `object` with `Recordstring, unknown`?
When you use Record<string, any>
, you don't get the error.
Just be aware that the object values are of type any
instead of unknown
: see 'unknown' vs. 'any'
interface Foo {
foo: string;
}
const foo: Foo = { foo: "foo" };
function fct(obj: Record<string, any>) {}
fct(foo);
Typescript Playground
JavaScript, overwrite object without losing reference
I found a solution after some thinking. It's probably not the most efficient solution, but it does the job for me. The time complexity could probably be better, and all suggestions of improvement are welcome. First parameter is the object to be extended, the second the one to extend with. The third is supposed to be a boolean, indicating whether the properties in a that doesn't exist in b should be removed or not.
function extend(_a,_b,remove){
remove = remove === undefined ? false : remove;
var a_traversed = [],
b_traversed = [];
function _extend(a,b) {
if (a_traversed.indexOf(a) == -1 && b_traversed.indexOf(b) == -1){
a_traversed.push(a);
b_traversed.push(b);
if (a instanceof Array){
for (var i = 0; i < b.length; i++) {
if (a[i]){ // If element exists, keep going recursive so we don't lose the references
a[i] = _extend(a[i],b[i]);
} else {
a[i] = b[i]; // Object doesn't exist, no reference to lose
}
}
if (remove && b.length < a.length) { // Do we have fewer elements in the new object?
a.splice(b.length, a.length - b.length);
}
}
else if (a instanceof Object){
for (var x in b) {
if (a.hasOwnProperty(x)) {
a[x] = _extend(a[x], b[x]);
} else {
a[x] = b[x];
}
}
if (remove) for (var x in a) {
if (!b.hasOwnProperty(x)) {
delete a[x];
}
}
}
else{
return b;
}
return a;
}
}
_extend(_a,_b);
}
How to overwrite object variables
You could destructure config
into the var1
, var2
, and var3
variables, using default property values. If config
isn't an object, destructure from an empty object instead so that those default parameters will be used:
function ObjFn(config) { const { var1=200, var2="querty", var3=555} = config instanceof Object ? config : {}; this.describe = function(){ console.log("var1: "+var1+" - "+"var2: "+var2+" - "+"var3: "+var3+" - "+"config: "+config+"\n") }}const instance = new ObjFn({ var1: 333 });instance.describe();
const instance2 = new ObjFn();instance2.describe();
Object literal may only specify known properties, and 'name' does not exist in type but the type exists
The problem is that ApexAxisChartSeries
is an Array type. So you ether need to change the ApexAxisChartSeries
to be an Object or return an array.
Playground with solutions
Overwrite an Object inside an Array of Objects
Use Object.assign after finding in array the object which matches the username
— in order to overwrite/modify the object data with another Object of data
const arr = [
{showMessage: true, username: "Joe"},
{showMessage: true, username: "Douglas"},
{showMessage: true, username: "Francis"}
]
const userDetails = {
showMessage: false,
username: 'Francis',
};
// Update user data by username (if object is found in array):
const oldDetails = arr.find(user => user.username === userDetails.username);
oldDetails && Object.assign(oldDetails, userDetails);
console.log(arr);
Object spread vs. Object.assign
For reference object rest/spread is finalised in ECMAScript 2018 as a stage 4. The proposal can be found here.
For the most part object assign and spread work the same way, the key difference is that spread defines properties, whilst Object.assign() sets them. This means Object.assign() triggers setters.
It's worth remembering that other than this, object rest/spread 1:1 maps to Object.assign() and acts differently to array (iterable) spread. For example, when spreading an array null values are spread. However using object spread null values are silently spread to nothing.
Array (Iterable) Spread Example
const x = [1, 2, null , 3];
const y = [...x, 4, 5];
const z = null;
console.log(y); // [1, 2, null, 3, 4, 5];
console.log([...z]); // TypeError
Object Spread Example
const x = null;
const y = {a: 1, b: 2};
const z = {...x, ...y};
console.log(z); //{a: 1, b: 2}
This is consistent with how Object.assign() would work, both silently exclude the null value with no error.
const x = null;
const y = {a: 1, b: 2};
const z = Object.assign({}, x, y);
console.log(z); //{a: 1, b: 2}
How do you loop through an object and replace text
This is related to my answer here.
The error code Exception: Invalid argument: replacement at Create_PDF(Code:37:8) at After_Submit(Code:13:19)
is caused by the null value of values['Timestamp'][0]
. If you try to print the data type of values['Timestamp']
, it will return a type object, since that object does not have value for index 0 to it will return a null value.
For entries that are type String, if you add [0]
to it, it will return only the first element of the string. Example you have "Test" string, adding [0] to it will return "T"
To fix that, just remove the [0]
in all of body.replaceText(..., values['...'][0])
entries.
OR
Loop through values
object by replacing the body.replaceText
entries in your code with this:
for (const key in values) {
body.replaceText("{{"+key+"}}", values[key]);
}
Example usage:
Form inputs:
Output:
Reference:
- JavaScript for..in
Related Topics
How to Condense Summable Metrics to a Unique Identifier in a Ruby Table
Why Does 'Defined' Return a String or Nil
Rails: How to Pass Custom Params to a Controller Method
Rails 3 Translations Within Models in Production
How to Remove Devise Password Resetting During Email Confirmation
I Want to Match All Punctuation in My Regexp Except Apostrophes. How to Do That in Ruby
Find a Unique Element in a Compound Array
Gracefully Shutting Down Sidekiq Processes
Instagram Ruby Gem - Unable to Reach Callback Url
How to Escape All Characters with Special Meaning in Regex
How to Write a Method That Counts the Most Common Substring in a String in Ruby
Proc Throws Error When Used with Do End
Rails Contact Form Not Working