SKP
SKP

Reputation: 137

Dynamic key with the value into the object into the react

I have denoted one code snippet shown here. Is there any way to assign the dynamic key with value inside the object like this:

var obj = {};
obj[key] = value;

How can we give the dynamic key value in object or array?

if (selectedOrder.customer.dataObj) {
  const {firstName,lastName,phoneNum} = selectedOrder.customer.dataObj
  obj["firstName"] = firstName ? firstName : "Error";
  obj["lastName"] = lastName ? lastName : "Error";
  obj["address"] = address ? address : "Error";
  obj["gender"] = gender ? gender : "Error";
  obj["dob"] = dob ? dob : "Error";
  obj["age"] = age ? age : "Error";
  obj["phoneNum"] = phoneNum ? phoneNum : "Error";
}

Upvotes: 1

Views: 4966

Answers (2)

Orelsanpls
Orelsanpls

Reputation: 23495

You can create an object from selectedOrder.customer.dataObj looping on it's keys. Then use the [] notation to create a dynamic key, here the variable being the name of the key is x.

Array.reduce is a method that takes an initial state, here an empty object, then loop on the given array and execute a given function for every entry of the provided array. tmp here is an accumulator. It's value is the value returned by the last iteration of the reduce loop.

const selectedOrder = {
  customer: {
    dataObj: {
      firstname: 'elon',
      lastName: 'musk',
      phoneNum: false,
    },
  },
};

const obj = Object.keys(selectedOrder.customer.dataObj).reduce((tmp, x) => {
  tmp[x] = selectedOrder.customer.dataObj[x] || 'Error';

  return tmp;
}, {});

console.log(obj);

Upvotes: 1

Rehan
Rehan

Reputation: 105

To use dynamic object keys, you have to use [].

For example,

var fooBar = 'phoneNum';
var obj = { address : 'Some address'};
obj[fooBar] = '900-009-2345';

Upvotes: 0

Related Questions