How to find through JSON array which has nested object elements - javascript

Below is my JSON array and I want to find if contact array has specific value or not.
data = [ { _id: 5a67294923aba20014e2fe5a,
customerLocation: '473 Victoria St, Singapore 198371',
customerName: 'UNIVERSAL',
id: 'UNI3L2',
customerType: 'customer',
contact:
[ 'Brian spilak',
'Brian spilak2',
'Brian spilak3',
'Brian spilak4',
'Brian spilak5' ] } ];
JAVASCRIPT
function findContact(data,con){
return data.contact.find(item => {
return item.data.contact == con;
})
}
console.log('Contact Name :', findContact(data,'Brian spilak2'));

item doesn't have data.contact property and your data response it an array, so you have to specify an index do work with:
function findContact(data,con){
return data[0].contact.find(item => {
return item == con;
})
}

You can use data.contact for contact data shown

You can use array#find with array#includes to check if a name exists in the contact property of the object.
var data = [ { _id: '5a67294923aba20014e2fe5a', customerLocation: '473 Victoria St, Singapore 198371', customerName: 'UNIVERSAL', id: 'UNI3L2', customerType: 'customer', contact: [ 'Brian spilak', 'Brian spilak2', 'Brian spilak3', 'Brian spilak4', 'Brian spilak5'] } ];
var result = data.find(o => o.contact.includes('Brian spilak2'));
console.log(result);

This one returns all the objects matching the name criteria in the array.
function filterName(data, srchName) {
return data.filter((obj) => {
return obj.contact.indexOf(srchName) !== -1
})
}
console.log(filterName(data, 'Brian spilak'));

Use indexOf.Since it is only one object data[0] is used to get the first object, if it is an array of object you can use forEach method
var data = [{
_id: '5a67294923aba20014e2fe5a',
customerLocation: '473 Victoria St, Singapore 198371',
customerName: 'UNIVERSAL',
id: 'UNI3L2',
customerType: 'customer',
contact: ['Brian spilak',
'Brian spilak2',
'Brian spilak3',
'Brian spilak4',
'Brian spilak5'
]
}];
function findContact(data, con) {
if (data[0].contact.indexOf(con) !== -1) {
return 'found';
} else {
return 'not found';
}
}
console.log('Contact Name :', findContact(data, 'Brian spilak2'));

Related

return a value of array that have special name

Im new in react js and I get a problem with my array... I want to return a value of my array that have contain name and adress .and all value are string thi is my data that I need
name :123,
adress:12569
const array = [
0: [ 'name','123' ],
1: [ 'adress','12569'],
2: ['family','4'],
];
You can run loop on the array and assign key-value for each of the array items.
const array = [
['name', '123'],
['adress', '12569'],
['family', '4'],
];
const res = {};
array.forEach((item) => {
res[item[0]] = item[1];
})
console.log(res);
In this case, you should use an Object.
const foo = {
name: '123',
adress: 'bar',
family: '4',
}
So, to access the propertys:
console.log(foo.name); // 123
console.log(foo.adress); // bar
console.log(foo.family); // 4
But if you are getting this information as an array, you can always transform it into an object.
It would make more sense for that data to be combined into a single object rather than a series of nested arrays, and then use find to locate the object that matches the query.
const data = [
{ name: 'Bob', address: '999 Letsbe Avenue', family: 4 },
{ name: 'Sally', address: '8 Treehouse Lane', family: 0 },
{ name: 'Joan', address: '85 Long Terrace', family: 6 }
];
// Accepts the data array, and a query object
function findFamily(data, query) {
// Iterate through the data array to `find`
return data.find(obj => {
// Split the query into key/value pairs
const queryEntries = Object.entries(query);
// And return only those objects where the
// object key/value matches the query key/value
return queryEntries.every(([ key, value ]) => {
return obj[key] === value;
});
// And if there are no matches return 'No match'
}) || 'No match';
}
console.log(findFamily(data, {
name: 'Bob',
address: '999 Letsbe Avenue',
family: 0
}));
console.log(findFamily(data, {
address: '999 Letsbe Avenue',
family: 4
}));
console.log(findFamily(data, {
name: 'Sally'
}));
Additional documentation
every
Destructuring assignment
Object.entries

Returning an array of all the pet names

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'));

How to map array of object dynamically

var data = [
{ extn: '2014', agentid: 'sravya', comments: '' },
{ extn: '2015', agentid: 'shalini', comments: '' }
]
const localityParameterSets = data.map(function(value){
return [
{name:"extn",value:{stringValue:value['extn']}},
{name:"agentid",value:{stringValue:value['agentid']}},
{name:"comments",value:{stringValue:value['comments']}}
]
})
console.log(JSON.stringify(localityParameterSets))
The above code is working fine but I need to make this name and value dynamically without hardcode i.e key value
for example "extn" string is hardcoded instead key value should come
"agentid" string is hardcoded instead key value should come
Use Object.entries and build the object dynamically.
var data = [
{
extn: '2014',
agentid: 'sravya',
comments: ''
},
{
extn: '2015',
agentid: 'shalini',
comments: ''
}
]
const localityParameterSets = data.map(function(value) {
return Object.entries(value).map( ([key,val]) => ({name:key, value:{stringValue:val}}))
})
console.log(localityParameterSets)
You could get the entries and map objects.
const
data = [{ extn: '2014', agentid: 'sravya', comments: '' }, { extn: '2015', agentid: 'shalini', comments: '' }],
result = data.map(o => Object.entries(o).map(([name, value]) => ({ name, value })));
console.log(result);

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