retrieving data from nested object - javascript

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>

Related

Compare and get difference from two object for patch api request in react js?

i m having two objects previous and new one, i trying to compare and get difference for those objects, send to as patch payload from patch api,
compare each properties in object if any of the property has any difference i want all those difference in new object as payload
How can i achieve this please help me find the solution?
Is there any lodash method for this solution?
let obj = {
Name: "Ajmal",
age: 25,
email: "ajmaln#gmail.com",
contact: [12345678, 987654321],
address: {
houseName: "ABC",
street: "XYZ",
pin: 67891
}
}
let obj2 = {
Name: "Ajmal",
age: 25,
email: "something#gmail.com",
contact: [12345678, 11111111],
address: {
houseName: "ABC",
street: "XYZ",
pin: 111
}
}
result payload i m expecting would look like
let payload = {
email: "something#gmail.com",
contact: [12345678, 11111111],
address: {
pin: 111
}
}
Mista NewbeedRecursion to your service:
const compare = (obj1, obj2) => {
const keys = Object.keys(obj1);
const payload = {};
keys.forEach((el) => {
const first = obj1[el];
const second = obj2[el];
let check;
if (first !== second) {
if (first instanceof Object && !(first instanceof Array))
check = compare(first, second);
payload[el] = check || second;
}
});
return payload;
};
Here is a approach with immer that may guide you to a proper solution
This is not a generic approach but makes things easier by relying on immer
import produce, { applyPatches, enablePatches } from "immer";
import { difference } from "lodash";
// once in your app
enablePatches();
let obj = {
Name: "Ajmal",
age: 25,
email: "ajmaln#gmail.com",
contact: [12345678, 987654321],
address: {
houseName: "ABC",
street: "XYZ",
pin: 67891
}
};
let obj2 = {
Name: "Ajmal",
age: 25,
email: "something#gmail.com",
contact: [12345678, 11111111],
address: {
houseName: "ABC",
street: "XYZ",
pin: 111
}
};
Gettig the patch updates
let fork = { ...obj };
let changes = [];
const updatedItem = produce(
fork,
(draft) => {
// object specific updates
draft.Name = obj2.Name;
draft.age = obj2.age;
draft.email = obj2.email;
draft.address.houseName = obj2.address.houseName;
draft.address.street = obj2.address.street;
draft.address.pin = obj2.address.pin;
const originalContact = original(draft.contact);
const contactDiff = difference(obj2.contact, originalContact);
console.log("diff", contactDiff);
if (contactDiff?.length) {
draft.contact = contactDiff;
}
},
(patches) => {
changes.push(...patches);
}
);
//Problem here => default values need to be given to state
// so the default values need to be excluded from the patch
let state = { contact: [], address: {} };
const patch = applyPatches(state, changes);
console.log("patch", patch);
logs changes op
contact: Array(1)
0: 11111111
address: Object
pin: 111
email: "something#gmail.com"
Hope this helps you in some way
Cheers

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

Update object property in javascript?

const [fields, setFields] = useState({
country: { country: "India" },
address: { street1: "street1", street2: "street2" },
});
This is my object. I want to update an inner property from this object
let id = 'street1'
let params = { ...fields, [id]: value }; //This will add a new prop
But i want to update the street1 inside the address object. How to do that?
Use this:
const updatedObject = {
...fields,
address: {
...fields.address,
[id]: value,
},
};
Try this
{...fields,address:{...fields.address,"street1":"abc"}}
let userAddress = {
country: { country: "India" },
address: { street1: "street1", street2: "street2" },
};
I believe the situation is to update the value of object that is nested , in this case street1.
Best way with ES6 would be to destructure and update the value.
userAddress = {
...userAddress,
address: { ...state.address, street1: newValue },
};

Added new Object to key from Object returned from Fetch & need to get new added values back out

I have JSON I am getting from an API and once that data is fetched, I am using another API to get geocode values and adding that to the object.
Here is the initial object after fetching:
{ approved: 1
body: "sample comments being made. "
categories: (4) [{…}, {…}, {…}, {…}]
created_at: "2020-12-18T19:38:43.000000Z"
email: "janedoe#gmail.com"
geocode: null
id: 7
image_id: "7"
is_moderated: 1
updated_at: "2020-12-21T20:57:04.000000Z"
zip: "60611"
}
Then I am using this loop to use each object's zip to get Geocoding info and add it to each object.
for (const property in data) {
getLocationInformation(data[property]);
const allApprovedComments = createCommentElement(data[property]);
commentContentParent.append(allApprovedComments);
}
This is what the getLocationInformation function looks like:
function getLocationInformation(comment) {
const fullPath = geoCode + '?address=' + comment.zip + '&key=' + geocodeApi;
fetch(fullPath)
.then(function fetchResponse(response) {
return response.json();
})
.then(function parseData(data) {
comment.geocode = {
county: data.results[0].address_components[2].long_name,
state: data.results[0].address_components[3].long_name,
stateAbbrv: data.results[0].address_components[3].short_name,
lat: data.results[0].geometry.location.lat,
lng: data.results[0].geometry.location.lng,
};
})
.catch(function fetchError(error) {
return error;
});
}
Then this is what the object that is returned:
{ approved: 1
body: "sample comments being made. "
categories: [{…}]
created_at: "2020-12-18T19:38:43.000000Z"
email: "janedoe#gmail.com"
geocode: {
county: "Cook County",
state: "Illinois",
stateAbbrv: "IL",
lat: 41.8925085,
lng: -87.61616959999999
},
id: 7
image_id: "7"
is_moderated: 1
updated_at: "2020-12-21T20:57:04.000000Z"
zip: "60611"
}
While, I am able to access the body key and all others, even if console.log(object) shows the geocode key to have values when I try to access the key like: object.geocode the value returned is always null. I don't understand why this is happening and any help with getting past this issue is appreciated!

How can I return or log all "name" values in this array of objects [duplicate]

This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Closed 3 years ago.
I have this array of objects. Im trying to get the "name" property to return or console log
I've tried using indexes(probably wrong) so Im pretty stuck.
var peopleArray = [{
name: "Harrison Ford",
occupation: "Actor"
},
{
name: "Justin Bieber",
occupation: "Singer"
},
{
name: "Vladimir Putin",
occupation: "Politician"
},
{
name: "Oprah",
occupation: "Entertainer"
}
]
Result should be:
["Harrison Ford", "Justin Bieber", "Vladimir Putin", "Oprah"]
Use map:
var peopleArray = [{name:"Harrison Ford",occupation:"Actor"},{name:"Justin Bieber",occupation:"Singer"},{name:"Vladimir Putin",occupation:"Politician"},{name:"Oprah",occupation:"Entertainer"}];
const res = peopleArray.map(({ name }) => name);
console.log(res);
ES5 syntax:
var peopleArray = [{name:"Harrison Ford",occupation:"Actor"},{name:"Justin Bieber",occupation:"Singer"},{name:"Vladimir Putin",occupation:"Politician"},{name:"Oprah",occupation:"Entertainer"}];
var res = peopleArray.map(function(e) {
return e.name;
});
console.log(res);
To select property of array object, you can use map() function
let result = peopleArray.map(function(item) { return item['name']; });
If you want to select many properties from array object, you can use map and object destructing
result = peopleArray.map(({ name, age }) => ({
name,
age
}));
var peopleArray = [{
name: "Harrison Ford",
occupation: "Actor",
age: 21
},
{
name: "Justin Bieber",
occupation: "Singer",
age: 22
},
{
name: "Vladimir Putin",
occupation: "Politician",
age: 23
},
{
name: "Oprah",
occupation: "Entertainer",
age: 24
}
]
let result = peopleArray.map(function(item) { return item['name']; });
console.log(result);
result = peopleArray.map(({ name, age }) => ({
name,
age
}));
console.log(result);
You can also use a map
var person = peopleArray.map(({name}) => name);
console.log(person)
//["Harrison Ford", "Justin Bieber", "Vladimir Putin", "Oprah"]
You can use a forEach to display them one after the other
peopleArray.forEach(person => {
console.log(person.name)
})
// "Harrison Ford"
// "Justin Bieber"
// "Vladimir Putin"
// "Oprah"

Categories

Resources