0

In my Angular2 app I am trying to figure out how to push a new object into an array that contains objects with three properties - when I only want to push one of those three properties. Take this array for instance:

locations = [
  { city: 'Los Angelas', zipcode: '90001', coordinates: 2321 },
  { city: 'New York', zipcode: '10001', coordinates: 3432 },
];

Here I want to ONLY push new zipcodes - not city names or coordinates. So, I'm assuming it would look like this after pushing a new object:

locations = [
  { city: 'Los Angelas', zipcode: '90001', coordinates: 2321 },
  { city: 'New York', zipcode: '10001', coordinates: 3432 },
  { zipcode: 20001 }
];

How would I handle this? Can I do this? Or would I need to pass null values for the other two properties?

2
  • can you please share a sample array with expected output? Commented Feb 15, 2017 at 4:12
  • locations.push({zipCode:'any value'}) ? Commented Feb 15, 2017 at 4:15

2 Answers 2

1

Do you mean for an object that already exists? In that case,

let index = locations.findIndex(element => element.city === city)
locations[index].zipcode = newZipCode

Array.findIndex is not fully supported yet, so you might have to polyfill it, or you could use the method from lodash.

EDIT: Per my comment, this should work just fine now that I know what you're looking for:

locations.push({ zipcode: newZipCode })
Sign up to request clarification or add additional context in comments.

8 Comments

No, I mean a new object (but that has just the one property - zipcode.
Then why can't you just use locations.push({ zipcode: newZipCode })
This is what I have for an array of objects that contains just one property: addZipcode(event) { this.zipcodes.push({ postalCode: this.newZipcode }); this.newZipCode = ''; this.addZipInput = false; event.preventDefault(); }
Is it not more complicated when the objects in the array have multiple properties? Maybe I'm overthinking this?
It's not. You can simply use push. All of the objects in the array do not have to match their properties.
|
1

Try this

locations = [
  { city: 'Los Angelas', zipcode: '90001', coordinates: 2321 },
  { city: 'New York', zipcode: '10001', coordinates: 3432 },
];

var tempObject = {
   zipcode : '10000'
}
locations.push(tempObject);

After pushing tempObject into locations array it will be like

locations = [
  { city: 'Los Angelas', zipcode: '90001', coordinates: 2321 },
  { city: 'New York', zipcode: '10001', coordinates: 3432 },
  { zipcode: '10000'}
];

Now when you will try to access locations[2].city or locations[2].coordinates then it will be undefined.

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.