Returning an array of all the pet names - javascript

If I were to create a function, were a persons name was entered, how would I return an array with the names of the pets from the object below, what would be the best method if I were to use a for loop to iterate over it? I've not quite learnt some of the ES6 features yet and i'm new to coding.
A typical array of owners is shown below:
[
{
name: 'Malcolm',
pets: ['Bear', 'Minu'],
},
{
name: 'Caroline',
pets: ['Basil', 'Hamish'],
},
];
Thanks for the fast replies! :)

It's pretty simple to achieve it:
you search for the corresponding owner with the find function, then, if you have an owner, you return the pets key, which is already an array according to the code provided. If you have no owner corresponding to the name entered, then you'll get "undefined", but you can customise this code to have an empty array if it better fits your needs.
const data = [{
name: 'Malcolm',
pets: ['Bear', 'Minu'],
}, {
name: 'Caroline',
pets: ['Basil', 'Hamish'],
}, ];
const getPetsByOwnerName = (ownerName) => {
const owner = data.find(d => d.name === ownerName);
return owner ? owner.pets : undefined;
}
const carolinePets = getPetsByOwnerName('Caroline');
console.log(carolinePets);
EDIT: author request to do it with a loop
const data = [{
name: 'Malcolm',
pets: ['Bear', 'Minu'],
}, {
name: 'Caroline',
pets: ['Basil', 'Hamish'],
}, ];
function getPetsByOwnerNameWithLoop(ownerName) {
for (let i = 0; i < data.length; i++) {
if (data[i].name === ownerName) {
return data[i].pets;
}
}
return undefined;
}
const carolinePets = getPetsByOwnerNameWithLoop('Caroline');
console.log(carolinePets);

let ownersArray = [ { name: 'Malcolm', pets: ['Bear', 'Minu'], }, { name: 'Caroline', pets: ['Basil', 'Hamish'], }, ];
const petArray = (owner, ownersArray) => {
let array = ownersArray.filter((arr) => arr.name===owner)
return array.length>0 ? array[0].pets : 'owner not found'
}
console.log(petArray("Caroline", ownersArray))

Try filter() method. The function returns an array of names from the filtered owner as a result.
Example code:
const arr = [
{ name: 'Malcolm', pets: ['Bear', 'Minu'], },
{ name: 'Caroline', pets: ['Basil', 'Hamish'], }
];
function petsNames(val) {
return arr.filter(x => x.name === val)[0].pets;
};
console.log(petsNames('Malcolm'));

Related

Trying to return a filter() value from an array of objects based on conditionals

I'm trying to return only a part of my object as an array based on conditionals but I'm kinda stumped.
I have an array of objects and I want to return an array of names for each key : value they fit in.
I do get only the unique pairings but I'm returning the food key:value as well and all of it is still inside an object not a new array. Some insight would be greatly appreciated. Newer to coding.
const organizeNames = function (foods) {
let foodNames = foods.filter((names) => {
if (names.food === 'oranges') {
return names.name;
}
});
console.log(foodNames);
};
console.log(
organizeNames([
{ name: 'Samuel', food: 'oranges' },
{ name: 'Victoria', food: 'pizza' },
{ name: 'Karim', food: 'pizza' },
{ name: 'Donald', food: 'pizza' },
])
);
You're really close here. What you need to incorporate is .map() to map your list of objects to a list of names. Your filter part works, partly by accident, so I've fixed it to be more correct (return names.food === 'oranges'), and then once you have your list of objects that match 'oranges' for their food, you map that filtered list into a list of names by doing .map(names => names.name)
const organizeNames = function (foods) {
let foodNames = foods.filter((names) => {
// only keep items whose .food property === 'oranges'
return names.food === 'oranges'; // returns true or false
}).map(names => {
// map the filtered list of objects into a list of names by
// returning just the object's .name property
return names.name;
});
return foodNames;
};
console.log(
organizeNames([
{ name: 'Samuel', food: 'oranges' },
{ name: 'Victoria', food: 'pizza' },
{ name: 'Karim', food: 'pizza' },
{ name: 'Donald', food: 'pizza' },
])
);
The filter() callback function should just return true or false. Then you can use map() to get a specific property from each of the filtered items.
const organizeNames = function(foods) {
let foodNames = foods.filter((names) => names.food == 'oranges').map(names => names.name);
return foodNames;
}
console.log(
organizeNames([{
name: 'Samuel',
food: 'oranges'
},
{
name: 'Victoria',
food: 'pizza'
},
{
name: 'Karim',
food: 'pizza'
},
{
name: 'Donald',
food: 'pizza'
},
])
);

Sequelize magic method returning null

Just a bit confused as to why this magic method is returning null. It's probably very simple, but I'm using methods I wouldn't normally (bulkingCreating) and can't currently see it.
Association: Country.hasOne(Capital, { foreignKey: 'countryId' });
Populating dummy data:
const countries = await Country.bulkCreate([
{ name: 'England' },
{ name: 'Spain' },
{ name: 'France' },
{ name: 'Canada' }
]);
const capitals = await Capital.bulkCreate([
{ name: 'London' },
{ name: 'Madrid'},
{ name: 'Paris' },
{ name: 'Ottawa' }
]);
countries.forEach((country, index) => {
country.setCapital(capitals[index]);
});
const country = await Country.findOne({where: {name: 'Spain'}});
console.log(country.name, Object.keys(country.__proto__)); // Spain / magic methods
const capital = await country.getCapital();
console.log(capital); // null
The table:
Am I wrong in thinking country.getCapital() should return the relevant entry?
As you might guess setCapital should be an async function because it makes changes in DB so you need to use for instead of forEach method that does not support async callbacks:
let index = 0;
for (const country of countries) {
await country.setCapital(capitals[index]);
index += 1;
}
It would be better to create countries one by one and create capitals for them not relying on the same indexes of both collections (DB might return created records in a different order).
If you are using Sequelize 5.14+, you can do this in 1 bulkCreate using include option.
const countries = await Country.bulkCreate([
{
name: 'England',
Capital: { // This keyname should be matching with model name.
name: 'London'
}
},
{
name: 'Spain',
Capital: {
name: 'Madrid'
}
},
...
],
{
include: Capital,
returning: true // If Postgres, add this if you want the created object to be returned.
}
);

How do you check if value exist in object of object's array?

I want to know which logic i should use to check every object's array of parent object contained in grand parent object
Hi guys i want to check if this value for example : "127.0.0.1" exists in this object (MyObject has like 2k objects in it)
{
"name" : MyObject
"value": [
{
"name" : "Object1",
"properties":{
"address" : [
"13.65.25.19/32",
"13.66.60.119/32",
]
}
},
{
"name" : "Object2",
"properties":{
"address" : [
"13.65.25.19/32",
"127.0.0.1",
]
}
}
]
}
Btw does include() needs to match the whole string or for example if 127.0.0.1 is like this in my object 127.0.0.1/32, i can still retrieve it even if there is a ip range ?
Your data is structured quite specifically, so you can write a custom method which you can call over and over again. It will check for a
const obj = {
name: 'MyObject',
value: [
{
name: 'Object1',
properties: {
address: ['13.65.25.19/32', '13.66.60.119/32'],
},
},
{
name: 'Object2',
properties: {
address: ['13.65.25.19/32', '127.0.0.1'],
},
},
],
};
const address = '127.0.0.1';
const includesAddress = (address) => {
for (const val of obj.value) {
if (val.properties.address.some((a) => address === a)) return true;
}
return false;
};
console.log(includesAddress(address));
Array.flatMap implementation
const obj = {
name: 'MyObject',
value: [
{
name: 'Object1',
properties: {
address: ['13.65.25.19/32', '13.66.60.119/32'],
},
},
{
name: 'Object2',
properties: {
address: ['13.65.25.19/32', '127.0.0.1'],
},
},
],
};
const address = '127.0.0.1';
const output = obj.value.flatMap(item => item.properties.address).includes(address);
console.log(output);
If you want check if the partial ip addess is included in the list, you should make use of a regex implementation.
Sample Implementation
const obj = {
name: 'MyObject',
value: [
{
name: 'Object1',
properties: {
address: ['13.65.25.19/32', '13.66.60.119/32'],
},
},
{
name: 'Object2',
properties: {
address: ['13.65.25.19/32', '127.0.0.1'],
},
},
],
};
const address = '13.65.25.19';
const regex = new RegExp(address, 'i')
const output = obj.value.flatMap(item => item.properties.address).filter(x => regex.test(x)).length > 0;
console.log(output);

Function Traversing Through An Array of Json Object needs to return one object

So I am not the best at writing functions so I am having a hard time wrapping a head around this. So I am trying to create a function that traverses through array of objects, and stops once it reads the name that is given it must return the number of the that person.
const array = [{name: 'Ann', phone: '575.580.1400', role: 'Developer'},
{name: 'Ben', phone: '575.641.4041', role: 'Manager'},
{name: 'Clara', phone: '512.717.5690', role: 'Developer'}];
const getNumber = (person, book ) => {
for (var x of book ) {
if( x == person) {
return number;}
return ('Not found');
}
}
I know I am missing how to call in the number, but I just can't think of how to do it.
First you need to access the key inside the object and return ('Not found'); is not in the right place. Secondly use === instead of ==.In your code if the function will return in the fist iteration only. Because if you search for Clara and in the if condition Ann will not be equal to Clara so it will return Not Found and will not iterate the remaining array
const array = [{
name: 'Ann',
phone: '575.580.1400',
role: 'Developer'
},
{
name: 'Ben',
phone: '575.641.4041',
role: 'Manager'
},
{
name: 'Clara',
phone: '512.717.5690',
role: 'Developer'
}
];
const getNumber = (person, book) => {
for (var x of book) {
if (x.name === person) {
return x.phone;
}
}
return ('Not found');
}
console.log(getNumber('Clara', array))
Alternatively you can also use array methods like find or filter
const array = [{
name: 'Ann',
phone: '575.580.1400',
role: 'Developer'
},
{
name: 'Ben',
phone: '575.641.4041',
role: 'Manager'
},
{
name: 'Clara',
phone: '512.717.5690',
role: 'Developer'
}
];
const num = array.find(item => item.name === 'Clara').phone;
console.log(num)
Below code helps to iterate through a JSON object and print the required value. You can use the required conditions in IF and print the desired values accordingly.
var json = [{name: 'Ann', phone: '575.580.1400', role: 'Developer'},
{name: 'Ben', phone: '575.641.4041', role: 'Manager'},
{name: 'Clara', phone: '512.717.5690', role: 'Developer'}];
for (var key in json) {
if (json.hasOwnProperty(key)) {
if(json[key].name=='Ben')
console.log(json[key].phone);
}
}
Try this
I am using some instead of foreach or other loops. some() method executes the callback function once for each element present in the array until it finds the one where callback returns a truthy value.
const getNumber = (person, book ) => {
let pnumber;
book.some((item) => {
if(item.name.toLowerCase()===person.toLowerCase()){
pnumber = item.phone;
return true;
}
})
return pnumber ? pnumber: "Not Found" ;
}
you can call it this way
getNumber('clara',array)
"512.717.5690"
getNumber('ben1',array)
"Not Found"

how do i create a new object based off an array and another object?

I am trying to create a new object based off an existing array. I want to create a new object that show below
{ jack: 'jack', content: 'ocean'},
{ marie: 'marie', content: 'pond'},
{ james: 'james', content: 'fish biscuit'},
{paul: 'paul', content: 'cake'}
const words = ['jack','marie','james','paul']
const myUsers = [
{ name: 'jack', likes: 'ocean' },
{ name: 'marie', likes: 'pond' },
{ name: 'james', likes: 'fish biscuits' },
{ name: 'paul', likes: 'cake' }
]
const usersByLikes = words.map(word => {
const container = {};
container[word] = myUsers.map(user => user.name);
container.content = myUsers[0].likes;
return container;
})
I am not getting the correct object, but instead it returns a list.
[ { jack: [ 'shark', 'turtle', 'otter' ], content: 'ocean'}, { marie: [ 'shark', 'turtle', 'otter' ], content: 'ocean' },
{ james: [ 'shark', 'turtle', 'otter' ], content: 'ocean' },
{ paul: [ 'shark', 'turtle', 'otter' ], content: 'ocean'} ]
What is the role of words array? I think the below code will work.
const result = myUsers.map(user => ({
[user.name]: user.name,
content: user.likes
}));
console.log('result', result);
In case, if want to filter the users in word array then below solution will work for you.
const result = myUsers.filter(user => {
if (words.includes(user.name)) {
return ({
[user.name]: user.name,
content: user.likes
})
}
return false;
});
You can achieve your need with a single loop.
The answer #aravindan-venkatesan gave should give you the result you are looking for. However important to consider:
When using .map() javascript returns an array of the same length, with whatever transformations you told it to inside map().
If you want to create a brand new object, of your own construction. Try using .reduce(). This allows you to set an input variable, i.e: object, array or string.
Then loop over, and return exactly what you want, not a mapped version of the old array.
See here for more details:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

Categories

Resources