0

Here is input that i gave

{
header: "dc_header.png"
icon: "dc_icon.png"
id: "DCA"
latitude: 38.89511
longitude: -77.03637
name: "Washington DC"
}

and i want to add distance in it like

{
header: "dc_header.png"
icon: "dc_icon.png"
id: "DCA"
latitude: 38.89511
longitude: -77.03637
name: "Washington DC"
**distance: 10**
}

How can i acheive this?

2 Answers 2

1

You can add a new key-value pair to an object this way:

objectName.distance = 10

You should change 'objectName' to the name of your object.

Sign up to request clarification or add additional context in comments.

Comments

0

If this is truly React question then potentially modifying the state is a bad idea. I propose that you spread the original object over a new object and add the additional property at the end.

const obj = {
  header: "dc_header.png",
  icon: "dc_icon.png",
  id: "DCA",
  latitude: 38.89511,
  longitude: -77.03637,
  name: "Washington DC"
};

const modifiedObj = {
  ...obj,
  distance: 10
};

console.log(modifiedObj);
.as-console-wrapper { top: 0; max-height: 100% !important; }

If you are mapping objects, you can do this similarly:

const distances = [ 10 ];

const objs = [{
  header: "dc_header.png",
  icon: "dc_icon.png",
  id: "DCA",
  latitude: 38.89511,
  longitude: -77.03637,
  name: "Washington DC"
}];

const modifiedObjs = objs.map((obj, index) => ({
  ...obj,
  distance: distances[index]
}));

console.log(modifiedObjs);
.as-console-wrapper { top: 0; max-height: 100% !important; }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.