Object assign key & value - if value is valid

object.assign array
object.assign deep copy
object.assign ie11
object.assign loop
object.assign w3schools
javascript add object to another object
object.assign map
object.assign polyfill

I think it;s dirty/unwanted question.

I have object name test, I just try to assign key and values(if value is valid).

In this below example x,y,z are variables, this variables are dynamic sometimes only we get value.

The below code is working fine, but I used everytime checked value is valid or not then i assign key and value into object.

Just I want to check some smart way to add key?

var test = {
    a: "1",
    b: "2"
}
var x = "3";
//here x value is dynamic, sometimes only we get value.
if (x) {
    test.c = x;
}

var y = "4";
//here y value is dynamic, sometimes only we get value.
if (y) {
    test.d = y;
}

var z = "5";
//here z value is dynamic, sometimes only we get value.
if (z) {
    test.e = z;
}

console.log(JSON.stringify(test));

If, as in your code, the tests always check to see whether the value is truthy before adding to the object, you could use a Proxy:

const test = {
    a: "1",
    b: "2"
};
const testProx = new Proxy(test, {
  set: (obj, prop, val) => {
    if (val) obj[prop] = val;
  }
});
testProx.c = 'foo';
testProx.d = null; // falsey, will fail the Proxy's test and will not be added to object
testProx.e = 'bar';
console.log(test);

ES6 Object.assign() Sample, [key] is an ES6 computed property. Here is a basic example: let obj = { [1 + 2]: '​Hello!' }; console.log(obj[3]);. In order to set an object’s key by variable, here are few steps to follow. Steps: First make a variable. Then make a object. Assign that variable a value. Here are few of the examples. Example-1: This example sets the object key by variable key and then inserts {“GFG_key”:”GFG_Val”} object to a array.

You can write it in a shorthand way like:

var x, y, z;

var test = {
  a: "1",
  b: "2",
  c: x || null,
  d: y || null,
  e: z || null
}
console.log(JSON.stringify(test));

Object.assign( ) key / value syntax, Also we can use the method Object.assign for that. user[key] and, if it's an object, then replicate its  Description. Object.keys() returns an array whose elements are strings corresponding to the enumerable properties found directly upon object. The ordering of the properties is the same as that given by looping over the properties of the object manually.

If it's coming from another variable then you can loop through that and check every key if the value is null and if not, add it to the test variable.

const main = {
x: 1,
y: 2,
z: 3
}

const test = {
a: 11,
b: 12,
c: 13
}

Object.keys(main).forEach((key) => {
if (main[key]) {
	test[key] = main[key]
}
});

console.log(test);

Objects, keys, Object.prototype.hasOwnProperty and the newer Object.assign. hasOwnProperty. hasOwnProperty is a method available on object instances that allows to  Dealing With Objects in JavaScript With Object.assign, Object.keys and hasOwnProperty This post is a sort of grab bag to help you explore a few very useful methods to help you manage your objects in JavaScript.

Since the description of your question is not that much clear, I am answering assuming,

  1. You need to validate every value you add into the object.
  2. You are finally using the stringified object for further processing.
  3. You need to automatically set the key for the values.

You may even use a proxy to do the same thing based on your requirement.

var test = {
	currentKey:0,
	add:function(val){
		if(val){
			this[String.fromCharCode('a'.charCodeAt()+(this.currentKey++))]=val;
		}
	},
	toJSON:function(){
		let obj={...this};
		delete obj.currentKey;
		delete obj.toJSON;
		return obj;
    }
}

let x = 90;
test.add(90);

let y = null;
test.add(y);

let z = 89;
test.add(z);

console.log(JSON.stringify(test));

Dealing With Objects in JavaScript With Object.assign, Object.keys , assign() supports both strings and symbols as keys. Copying versus assignment. Properties in the target object are created via assignment (  Object.assign() Method Among the Object constructor methods, there is a method Object.assign() which is used to copy the values and properties from one or more source objects to a target object. It invokes getters and setters since it uses both [[Get]] on the source and [[Set]] on the target.

ECMAScript 6: merging objects via Object.assign(), How to store a key=> value array in JavaScript ? How to detect HTTP or Object.​assign() does not throw on null or undefined source values. Applications:. The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object. It will return the target object.

Object.assign( ) in JavaScript, If an object has a method with that key, it becomes iterable: The method must return an Both kinds of property keys: Object.assign() is aware of both strings and  To iterate over an object: for (let key in obj) loop. Objects are assigned and copied by reference. In other words, a variable stores not the “object value”, but a “reference” (address in memory) for the value. So copying such a variable or passing it as a function argument copies that reference, not the object.

14. New OOP features besides classes, The deepObject function takes all of the keys of an object and iterates over them, describe('assign v1 (copy props)', () => { it('assigns objects  var value = jsObj["key" + i]; The [ ] operator there is doing precisely the same thing in both instances. The fact that in one case the object involved happens to be an array is unimportant, in other words.

Comments
  • Are the tests always truthy-checkers, that is, if (someVar) // assign someVar to prop of object ?
  • So you want, if there is a key, add that key and value, if not add a new key and the value. am I correct?
  • "sometimes only we get value" what?
  • @sorxrob, x,y,z values are get from backend,
  • So do you want to keep keys in order a,b,c,d... whenever you add a new value to the object? Is that what you need?
  • Thanks, I expected like this only.
  • Possible to add the code (testProx ) inside the function ? It will use multiple places.
  • Inside which function? What are you referring to?
  • Expecting create new function, then will move that code(testProx ) there.. because I will use multiple places using same function. Example I have test object, some other places have xxx object..
  • Sorry for my bad english
  • If the value is null or undefined then don;t add the key's (c,d,e)