Pulling array from object - javascript

Im trying to pull the gpa numbers from the array that is in the object and have them displayed in the console but my code keeps giving me undefined '0' error. Any help would be appreciated.
var fsInfo = {
name: 'John Doe',
address:{
street: '123 Some Street ',
city: 'Town, ',
state: 'HI',
gpa: [3.0,4.0,2.0]
}
}
console.log("GPA: " + fsInfo.gpa['0'],fsInfo.gpa['1'],fsInfo.gpa['2'])

Use
console.log("GPA: " + fsInfo.gpa[0],fsInfo.gpa[1],fsInfo.gpa[2])
Note: Array indices are numbers.
In your case, they are inside address. So you should do
console.log("GPA: " + fsInfo.address.gpa[0],fsInfo.address.gpa[1],fsInfo.address.gpa[2])
If your object had been like this
var fsInfo = {
name: 'John Doe',
address:{
street: '123 Some Street ',
city: 'Town, ',
state: 'HI'
},
gpa: [3.0,4.0,2.0]
}
then
console.log("GPA: " + fsInfo.gpa[0],fsInfo.gpa[1],fsInfo.gpa[2])
will work.

Related

How to make a variable using keys from literal object, javascript

In an exercise, I have to make a variable called "fullAddress" that contains everything in a given literal object except for the first key.
I found a solution that sort of works, but I feel like there is a better way to do it. Also, I can't figure out how to efficiently put space between the values in the variable.
The exercise says the final result should look something like this:
39 Johnson Ave, Brooklyn, NY, 11206
But mine looks like this:
39 Johnson AveBrooklynNY11206
Literal Object provided in exercise:
const restaurant = {
name: 'Ichiran Ramen',
address: `${Math.floor(Math.random() * 100) + 1} Johnson Ave`,
city: 'Brooklyn',
state: 'NY',
zipcode: '11206',
}
My solution:
let fullAddress = restaurant.address + restaurant.city + restaurant.state + restaurant.zipcode;
Given an array of strings, you can use values.join(', ') to put commas between the values cleanly. Then you could do e.g. [restaurant.address, restaurant.city, restaurant.state, restaurant.zipcode].join(', ').
If you wanted to do this more generically for any object, you could use Object.values(restaurant).slice(1).join(', ') to dynamically get all values after the first and comma delimit them.
In this case though, I think it makes the most sense to just explicitly append with commas since it's an address format (maybe you don't want a space after the zip code for example), so something like restaurant.address + ', ' + restaurant.city + ...
Regarding spaces (and commas), you can use a template string as done for restaurant.address.
const restaurant = {
name: 'Ichiran Ramen',
address: `${Math.floor(Math.random() * 100) + 1} Johnson Ave`,
city: 'Brooklyn',
state: 'NY',
zipcode: '11206',
};
let fullAddress = `${restaurant.address}, ${restaurant.city}, ${restaurant.state}, ${restaurant.zipcode}`;
console.log(fullAddress); // 39 Johnson Ave, Brooklyn, NY, 11206
Next, notice we're actually joining all the address-parts with the same delimiter: ', '. This means we can use [].join() instead.
const restaurant = {
name: 'Ichiran Ramen',
address: `${Math.floor(Math.random() * 100) + 1} Johnson Ave`,
city: 'Brooklyn',
state: 'NY',
zipcode: '11206',
};
let addressParts = [restaurant.address, restaurant.city, restaurant.state, restaurant.zipcode];
let fullAddress = addressParts.join(', ');
console.log(fullAddress); // 39 Johnson Ave, Brooklyn, NY, 11206
Lastly, (if you want to get fancy), note that restaurant. is repeated. This can be avoided with [].map().
const restaurant = {
name: 'Ichiran Ramen',
address: `${Math.floor(Math.random() * 100) + 1} Johnson Ave`,
city: 'Brooklyn',
state: 'NY',
zipcode: '11206',
};
let fullAddress = ['address', 'city', 'state', 'zipcode']
.map(key => restaurant[key])
.join(', ');
console.log(fullAddress); // 39 Johnson Ave, Brooklyn, NY, 11206
You can take out all the values from the restaurant object, remove the first element and then use join to get the desired string
const restaurant = {
name: 'Ichiran Ramen',
address: `${Math.floor(Math.random() * 100) + 1} Johnson Ave`,
city: 'Brooklyn',
state: 'NY',
zipcode: '11206',
}
const fullAddress = Object.values(restaurant).slice(1).join(', ');
console.log(fullAddress);

I've object {name: 'John', 'surname': 'Johnson', 'age': '20'}

Please tell me, I need to write a function that writes the corresponding values
into the variables name, surname and age.
How can this be implemented?
let user = {
name: 'John',
surname: 'Johnson',
age: '20',
};
let{name, surname, age} = user;
document.write(name + ' ' + surname + ' ' + age);
Ummm
function writeUser(user){
document.write(user.name + " " + user.surname + " " +user.age)
}
?
Let's see if this is something in the lines of what you're looking for:
const user = {
name: 'John',
surname: 'Johnson',
age: '20',
};
function updateUser(user) {
user.name = "New name";
user.surname = "New surname";
user.age = "New age";
}
updateUser(user);
const { name, surname, age } = user;
document.write(name + ' ' + surname + ' ' + age);
By adding an other parameter to this function you might make it more useful, like this:
function updateUser(user, overrides) {
Object.assign(user, overrides);
}
updateUser(user, { age: '30', name: 'New name' });
This would change the age and name but leave the surname, but it modifies the input user which isn't really a good pattern, better to return a new object instead:
function updateUser(user, overrides) {
return Object.assign({}, user, overrides); // First assign user to the empty object, then assign the overrides to that new object
}

retrieving data from nested object

I have this object example only:
{
id: 301
payload: {
1: {
house_no: 1234,
city: London
},
2: {
house_no: 0000
city: Paris
}
}
}
I need to extract only the house_no and city for both 1 and 2.
I have tried for loping through like so: *Address passed to the loop is the object above
let item = [];
for(let x in address){
item.push(item[x]);
}
console.log('Address', item.city);
This gives me array with undefined elements:
[
0: undefined
1: undefined
]
Could you guys please help me just retrieving the data i need for each 1,2 : house_no and city
Object.values(address.payload).map(({ house_no, city }) => ({ house_no, city }));
This goes over each value in address.payload and returns an array of objects with house_no and city.
const address = {
id: 301,
payload: {
1: {
house_no: 1234,
city: 'London'
},
2: {
house_no: 0000,
city: 'Paris'
}
}
};
const result = Object.values(address.payload).map(({ house_no, city }) => ({ house_no, city }));
console.log(result);
You can just directly access it as below,
const {1: obj1, 2: obj2} = address.payload;
In here javascript will destructure the payload and assign object 1 into 1 and object 2 into 2. There were some missing commas and quotations in the object which you provided. Therefore I added that also below. Now, obj1 and obj2 will have the 1 and 2 objects where you can extract the data you need out of them easily.
let address = {
id: 301,
payload: {
1: {
house_no: 1234,
city: "London"
},
2: {
house_no: 0000,
city: "Paris"
}
}
};
const {1: obj1, 2: obj2} = address.payload;
console.log(obj1);
console.log(obj1.city);
console.log(obj1.house_no);
You can access object properties directly without looping:
<script>
var obj = {
id: 301,
payload: {
1: {
house_no: 1234,
city: "London"
},
2: {
house_no: 0000,
city: "Paris"
}
}
}
var address1 = obj.payload[1].house_no + " " + obj.payload[1].city;
var address2 = obj.payload[2].house_no + " " + obj.payload[2].city;
</script>

javascript - map with conditionally altered nested field

Given an array such as:
people = [
{
name: 'Bob',
sex: 'male',
address:{
street: 'Elm Street',
zip: '12893'
}
},
{
name: 'Susan',
sex: 'female',
address:{
street: 'Hickory Street',
zip: '00000'
}
}
]
I am trying to write a function which will alter specific instances of '00000' in the nested field 'zip' to the string '12893' and return a new array identical to the initial array except with the corrected values. My attempt at a function so far is:
function zipFix (initialArray) {
return initialArray.map(function(person) {
if(person.address.zip === '00000')
person.address.zip = "12893"
return person
});
}
I know this function is altering the values in 'initialArray', which isn't supposed to happen. How can I go about writing my function so that I can effectively use the map function to create a new, corrected array? Thanks.
While map-ing over the values, you will need to create a copy of each object. The easiest way to do so is with the object spread syntax ({...obj}).
This will "spread" all the values (name, adress, etc) into a new object. So any changes won't mutate it. However, it's "shallow" meaning it will be a new object but its values are the same. So since address is also an object we need to copy that as well, hence the reason for the nested spread of the address value as well.
people = [{
name: 'Bob',
sex: 'male',
address: {
street: 'Elm Street',
zip: '12893'
}
},
{
name: 'Susan',
sex: 'female',
address: {
street: 'Hickory Street',
zip: '00000'
}
}
]
function zipFix(initialArray) {
return initialArray.map(function(person) {
// Create a new "copy" of the person. Using object spread
// will create a "shallow" copy, so since address is also an
// object it will have to be spread (same for other objects that might
// be mutated).
const newValue = { ...person, address: { ...person.address }}
if (newValue.address.zip === '00000') {
newValue.address.zip = "12893";
}
return newValue
});
}
console.log(zipFix(people))
console.log(people) // unchanged
You need to return values from callback function too, also make a copy of element before assigning to avoid mutability
const people = [{name: 'Bob',sex: 'male',address:{street: 'Elm Street',zip: '12893'}},{name: 'Susan',sex: 'female',address:{street: 'Hickory Street',zip: '00000'}}]
function zipFix (initialArray) {
return initialArray.map(function(person) {
let newObj = JSON.parse(JSON.stringify(person))
if(newObj.address.zip === '00000')
newObj.address.zip ="12893"
return newObj
});
}
console.log(zipFix(people))
people = [{
name: 'Bob',
sex: 'male',
address: {
street: 'Elm Street',
zip: '12893'
}
},
{
name: 'Susan',
sex: 'female',
address: {
street: 'Hickory Street',
zip: '00000'
}
}
]
function zipFix (initialArray) {
return (initialArray.map(({address, ...p}) => (
address.zip !== '00000' ? { ...p, address } : {
...p,
address: {
...address,
zip: '12893'
}
}
)));
}
console.log(zipFix(people));
You can do:
const people = [{name: 'Bob',sex: 'male',address: {street: 'Elm Street',zip: '12893'}},{name: 'Susan',sex: 'female',address: {street: 'Hickory Street',zip: '00000'}}]
const zipFix = people.map(({address, ...p}) => ({
...p,
address: {
...address,
zip: address.zip === '00000' ? '12893' : address.zip
}
}))
console.log(zipFix)

This in function inside object Javascript

what is the wrong in this code , function fullAdress
i don't know what is the wrong in my code,
help my to fix it
var person = {
firstName: 'Ammar',
lastName: 'Gais',
age:21,
adress:{
street:'king road',
city:'atabra',
state:'River Nile'
fullAdress: function(){
return this.street+" "+this.city+" "+this.state;
}
},
fullName: function() {
return this.firstName+" "+this.lastName;
}
}
You are missing a comma after 'River Nile'. It is always recommended to look at the browser console for such errors. Even the object has properties or methods, everything should be separated by comma:
var person = {
firstName: 'Ammar',
lastName: 'Gais',
age: 21,
adress: {
street: 'king road',
city: 'atabra',
state: 'River Nile',
fullAdress: function() {
return this.street + " " + this.city + " " + this.state;
}
},
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
console.log(person.adress.fullAdress());
console.log(person.fullName());

Categories

Resources