Destructuring an array of objects (es6) - javascript

I'm wondering how to destructure an array of objects. I'm attempting to destructure country from the partner array. It is a project requirement that partner be an array of objects, even though there should only ever be one partner country per obj.
arr = [
{ title: "Title A",
desc: "Desc A",
role: {role_desc: "Role Desc A", role_name: "Role A"},
partner: [{country: "Brazil", region: "SA"}]
},
{ title: "Title B",
desc: "Desc B",
role: {role_desc: "Role Desc B", role_name: "Role B"},
partner: [{country: "US", region: "NA"}]
}
]
I am able to populate a table with data for all fields except partner.
arr.map(
({ title, desc, role: {role_name}, partner: [{country}] }) =>
({ title, desc, role: {role_name}, partner: [{country}] })
);
I've referred to Destructure object properties inside array for all elements and Destructuring an array of objects with es6, and it looks like it is not possible to do this without transforming the data first.
Any help would be appreciated (and apologies for the dupe).

You can simply use default value when you want to handle the case when partner is empty array,
const arr = [{ title: "Title A",desc: "Desc A",role: {role_desc: "Role Desc A", role_name: "Role A"},partner: [{country: "Brazil", region: "SA"}]},{ title: "Title B",desc: "Desc B",role: {role_desc: "Role Desc B", role_name: "Role B"},partner: [{country: "US", region: "NA"}]},{ title: "Title C",desc: "Desc C",role: {role_desc: "Role Desc C", role_name: "Role C"},partner: []}]
const final = arr.map(
({ title, desc, role: {role_name}, partner}) =>
({ title, desc, role: {role_name}, partner:[ {country} = {country: undefined } ] })
);
console.log(final)
That being said we should keep our code as readable as possible, here it becomes so hard on eyes instead of trying to save one extra line, we should opt for making it more readable
const arr = [{ title: "Title A",desc: "Desc A",role: {role_desc: "Role Desc A", role_name: "Role A"},partner: [{country: "Brazil", region: "SA"}]},{ title: "Title B",desc: "Desc B",role: {role_desc: "Role Desc B", role_name: "Role B"},partner: [{country: "US", region: "NA"}]},{ title: "Title C",desc: "Desc C",role: {role_desc: "Role Desc C", role_name: "Role C"},partner: []}]
const final = arr.map(
({ title, desc, role: {role_name}, partner}) => {
let country = partner[0] && partner[0].country || undefined
return { title, desc, role: {role_name}, partner:[ {country}] }
}
);
console.log(final)

I was overlooking a very simple answer due to an equally simple error:
arr.map(
({ title, desc, role: {role_name}, partner}) =>
({ title, desc, role: {role_name}, partner: (partner[0] && partner[0].country) || 'Undefined' })
);
Every item in the array did not necessarily have a "country" property. For certain items, partner is just an empty array. The above fixed the issue.
I agree that it doesn't make sense to make partner an array if it will only ever contain one object. Client requirements, however.

Related

Merging two objects with a list of p1_name and p1_email as well as p2_name and p2_email and the second object order of these fields may be different

The setup: I have an object of 'Student' each of which stores parent info as keys to the student. These keys look like:
const s1 = {
name: "student Name",
p1_name: "Parent one name",
p1_email: "ParentOne#email.com",
p2_name: "Parent Two name",
p2_email: "ParentTwo#email.com",
}
Then the student comes in with new info:
const s1_v2 = {
name: "New Name"
p1_name: "Parent one name",
p1_email: "ParentOneNewEmail#email.com",
p2_name: "Parent Two name",
p2_email: "ParentTwoNewEmail#email.com",
}
I could easily merge these with s = {...s1, ...s1_v2} If the parents match up. However the order might have changed from p1 and p2. Or I have no p2 and my p1 values are what my p2 values are. Thus if I merge them simply as above I would end up with:
const s1 = {
name: "student Name"
p1_name: "Parent Two name",
p1_email: "ParentTwo#email.com",
p2_name: "Parent two name",
p2_email: "ParentTwo#email.com",
}
Yes I know the data structure is poor, it's what I'm working with right now. Down the road I plan to move it to a relational association.
So the question becomes how can I check my fields to make sure i merge them correctly?
the order might have changed from p1 and p2
That is not a problem.
const s1 = {
name: "student Name",
p1_name: "Parent one name",
p1_email: "ParentOne#email.com",
p2_name: "Parent Two name",
p2_email: "ParentTwo#email.com",
}
const s1_v2 = {
name: "New Name",
p1_name: "Parent Two name",
p1_email: "ParentTwoNewEmail#email.com",
p2_name: "Parent one name",
p2_email: "ParentOneNewEmail#email.com",
}
const s = {...s1, ...s1_v2}
console.log(s)
I have no p2 (in the new values... I assume)
You would need to delete parent #2 then...
const s1 = {
name: "student Name",
p1_name: "Parent one name",
p1_email: "ParentOne#email.com",
p2_name: "Parent Two name",
p2_email: "ParentTwo#email.com",
}
const s1_v2 = {
name: "New Name",
p1_name: "Parent Two name",
p1_email: "ParentTwoNewEmail#email.com",
}
const s = {...s1, ...s1_v2}
if(!("p2_name" in s1_v2)){
delete s.p2_name
delete s.p2_email
}
console.log(s)

Deep copy props that contains object arrays and string arrays

Goal:
I need to have the props read and writable in the component.
Challenges:
Props are read only. I believe deep coping/cloning will solve this.
I cant figure out how to deep copy the props as it contains different variable types, such as string arrays and object arrays.
These are the variables:
var data = [
{ID: 5, First: "first", Middle: null, Last: "last", Job Listing ID: null, …},
{ID: 6, First: "first", Middle: null, Last: "last", Job Listing ID: null, …},
…
]
var default_refine_toggle_display = [
"ID",
"CV",
"C Letter",
"NDA",
"Photo",
"Address",
"First",
"Middle",
"Last",
"Email",
"Job Title",
"Status",
]
var fake_prop_change_name = {
applicant_id: "ID",
recruiter_id: "Recruiter ID",
cover_letter_id: "C Letter",
nda_id: "NDA",
file_photo_id: "Photo",
resume_cv_id: "CV",
file_address: "Address",
first_name: "First",
middle_name: "Middle",
last_name: "Last",
gender: "Sex",
personal_email: "Email",
building_number: "Building #",
street_number: "Street #",
street_name: "Street Name",
town_name: "Town Name",
state: "State",
country: "Country",
applicant_status_id: "Status ID",
status_datetime_change: "Change Datetime",
why_should_we: "Why Should We",
job_listings_id: "Job Listing ID",
name: "Status",
Job_title_Status: "Job Title",
personal_email:"Email"
}
var column_order = ["applicant_id", "Status","Job_title_Status", 'first_name', "middle_name", "last_name", "personal_email"];
var make_view_file = ["CV", "C Letter", "NDA","Photo","Address"]
This is how those variables are being passed to the component:
<Component_table
default_refine_toggle_display={default_refine_toggle_display}
fake_prop_change_name={fake_prop_change_name}
column_order={column_order}
make_view_file={make_view_file}
data={database_data['Job Applications']}
/>
What I've tried
var props_editable = Array.from(props)
var props_editable = props
What I'm trying:
I was thinking to maybe deep clone each prop individually and then store them in a new array. That way I can handle the deep clone of each prop variable type as it needs.
What are your thoughts on this?
I am finding dealing with arrays and objects to require a lot of brain power for me and cant seem to figure this out.
If you want to clone an array, you could use ES6 spread syntax. It could be helpful in cloning arrays and objects.
Cloning array of objects
var data = [
{
ID: 5,
First: "first",
Middle: null,
Last: "last",
"Job Listing ID": null,
},
{
ID: 6,
First: "first",
Middle: null,
Last: "last",
"Job Listing ID": null,
},
];
const copyData = [...data];
console.log(copyData);
clone an object
const obj = {
name: "Praveen",
address: {
streetName: "Amphitheatre streer",
blockNumber: 8,
Country: "USA",
},
};
const cloneObj = { ...obj };
console.log(obj);
console.log(cloneObj);

javascript error SyntaxError: missing : after property id

Trying to make an array of strings inside array of objects and getting an error saying SyntaxError: missing : after property id for the code below in javascript
let movies = [
{
movie title: 'Avengers: Age of Ultron',
release year: '2015',
rating:'7.3',
"genres"=[0:"Action",1:"Adventure",2:"Sci-Fi"]
},
{
movie title: 'The Dark Knight',
release year:'2008',
rating:'9.0',
genres:["Action","Crime","Drama"]
},
{
movie title: 'Forrest Gump',
release year:'1994',
rating:'8.8',
genres:["Drama","Romance"]
},
{
movie title: 'Inception',
release year:'2010',
rating:'8.8',
genres:["Action","Adventure","Sci-Fi"]
},
{
movie title: 'The Matrix',
release year:'1999',
rating:'8.7',
genres:["Action","Sci-Fi"]
},
{
movie title: 'Border',
release year:'1997',
rating:'7.9',
genres:["Action","Drama","History"]
}
];
There are two mistakes in your code.
If JSON object key contains ' ', you should write ".
You don't need to write an index to your JSON object value.
Here's the updated code.
let movies = [
{
"movie title": 'Avengers: Age of Ultron',
"release year": '2015',
rating:'7.3',
genres:["Action", "Adventure", "Sci-Fi"]
},
{
"movie title": 'The Dark Knight',
"release year":'2008',
rating:'9.0',
genres:["Action","Crime","Drama"]
},
{
"movie title": 'Forrest Gump',
"release year":'1994',
rating:'8.8',
genres:["Drama","Romance"]
},
{
"movie title": 'Inception',
"release year":'2010',
rating:'8.8',
genres:["Action","Adventure","Sci-Fi"]
},
{
"movie title": 'The Matrix',
"release year":'1999',
rating:'8.7',
genres:["Action","Sci-Fi"]
},
{
"movie title": 'Border',
"release year":'1997',
rating:'7.9',
genres:["Action","Drama","History"]
}
];

How can I make a Search String to search like an IN filter on an Array of Object

The filter on UI allows a user to search using the IN criterion. The search string will then become the property of the condition Object.
The search string will look like "1234,5436,8765" and then the condition Object will be like ```
condition: {
field: "Id",
operator: "in",
value: "1234,5436,8765"
}
Now as this is going to be IN filter, so whar criterion should I use so as to make the value search like IN criterion from the results Array.
e.g. for a like filter, I will set my value property like this %1234% so as to search this in the results Array.
Your question isn't clear so try to edit it to make it clearer.
I made a huge assumption here in my answer (as it is not clear from the question):
You could do it with a switch statement and then your various filter methods for each case.
You could do it more robustly, but until the question is clearer, it doesn't make much sense to build this solution out.
const myArrOfObs = [
{Id: 1234, title: "some title 1", other: "some other val 1"},
{Id: 2468, title: "some title 2", other: "some other val 2"},
{Id: 8240, title: "some title 3", other: "some other val 3"},
{Id: 9371, title: "some title 4", other: "some other val 4"},
{Id: 5436, title: "some title 5", other: "some other val 5"},
{Id: 8365, title: "some title 6", other: "some other val 6"},
{Id: 8765, title: "some title 7", other: "some other val 7"},
{Id: 3946, title: "some title 8", other: "some other val 8"}
];
const condition = {
field: "Id",
operator: "in",
value: "1234,5436,8765"
};
function filterArr(arr, cond) {
switch (cond.operator){
case "in":
const valueArr = cond.value.split(',');
return arr.filter(item => valueArr.includes(item[cond.field].toString()));
//case "like":
//return arr.filter( ... );
default:
return null;
}
}
const myFilteredArr = filterArr(myArrOfObs, condition);
console.log(myFilteredArr);

How to create Object with dynamic keys with value from string in pure js?

I'm trying to create an object with dynamic keys with key ID and value as a name from a string that I'm getting through API.
Below is my API
["PHP", "Project Management", "PHP dynamic website", "Ecommerce", "Magento", "Magento Websites"]
I want to convert it to following response
[
{ id: 0, name: "PHP" },
{ id: 1, name: "Project Management" },
{ id: 2, name: "PHP dynamic website" },
{ id: 3, name: "Ecommerce" }
]
You can map each name to an object which uses the index as the id and the value as the name property:
const arr = ["PHP", "Project Management", "PHP dynamic website", "Ecommerce", "Magento", "Magento Websites"];
const res = arr.map((name, id) => ({id, name}));
console.log(res);
Just use a forEach loop, and use the iterator as the key:
var apiResponse = ["PHP", "Project Management", "PHP dynamic website", "Ecommerce", "Magento", "Magento Websites"],
newResponse = [ ];
apiResponse.forEach(function(name, index) {
newResponse.push({ id: index, name: name });
});
console.log(newResponse);
Considering your usecase: Assuming newArr is the type of array you want
// ar is the initial array
ar=["PHP", "Project Management", "PHP dynamic website", "Ecommerce", "Magento", "Magento Websites"];
newArr=[];
for(i=0;i<ar.length;i++){
let obj={id:i,name:ar[i]};
newArr.push(obj);
}
console.log(newArr);
There no dynamic keys in here tho, all your objects and their keys look the same... Simply use the array.forEach() method to loop on all array values and push them into object into a new array:
let res = [];
sourceArr.forEach( (name, index) => {
res.push( {id: index, name: name} );
}
Easy as that.
I used traditional way. hope you are looking for this one.
B = ["PHP", "Project Management", "PHP dynamic website", "Ecommerce", "Magento", "Magento Websites"]
result = [];
for (i=0;i<B.length;i++)
{
result[i] = "{id:"+[i]+ "name:"+B[i]+"}";
}
console.log(result);

Categories

Resources