loop through a dynamic key of an object in a array [duplicate] - javascript

This question already has answers here:
JavaScript property access: dot notation vs. brackets?
(17 answers)
Closed 11 months ago.
I have 2 arrays. The one contains the name of all the keys of the 2nd array like the following.
const additionalFields = ['phoneNumbers', 'ageOrDobs', 'genders', 'usernames', 'employments', 'educations', 'websites', 'affiliatedOrganizations'];
const fields= [{
affiliatedOrganizations: []
ageOrDobs: []
educations: []
emails: [{…}]
employments: []
genders: []
locations: [{…}]
names: [{…}]
phoneNumbers: []
usernames: []
websites: []
}]
Now, I want to loop through the additionalFields based on the value I receive I want to check if the key of fields have length greater than 0. For example.. fields.phonenNumbers.length > 0 but the key phoneNumbers will be coming from loop
additionalFields.map((opts) => {
if(fields.opts.length > 0){ //this one doesn't work...
//do something
}
}
I am using typescript and fields have a interface related to the values in it as shown above. Please help me with this... thank you!!

Just use the Bracket notation:
additionalFields.map((opts) => {
if(fields[opts].length > 0){ //this one doesn't work...
//do something
}
}
Example:
const person = {
firstname: 'John',
lastname: 'Doe'
}
const key = "firstname"
console.log(person[key]) // John

Related

Javascript Map() object has confusing behaviour [duplicate]

This question already has answers here:
Object copy using Spread operator actually shallow or deep?
(4 answers)
Closed 6 months ago.
I have a use case that I thought the Map object would be perfect for but there is confusing behaviour that appears to me as a bug, but Im after any information as to why this happens and possibly a solution to the behaviour.
For instance, say I have 2 objects:
const obj1 = { name: "John" };
const obj2 = { name: "Jane", age: 35 };
And I have defined and extra object for extra properties to add to both objects later:
const extProps = { gender: "unspecified", children: [] };
Create a new Map object and add the 2 objects:
const map = new Map();
map.set(obj1.name, obj1);
map.set(obj2.name, obj2);
Due to the objects being reference types I can assign the extra props like so:
Object.assign(obj1, { ...extProps });
Object.assign(obj2, { ...extProps });
Now I can get the values from the map using the keys like:
const johnObj = map.get("John");
const janeObj = map.get("Jane");
And the object have all the extra props like expected. The following statements update the individual objects in the map:
janeObj.gender = "female";
johnObj.age = 45;
Here is where the confusing behaviour I see is happening...
If I add an entry to the children array of either objects, it updates both
johnObj.children.push("jack");
obj2.children.push("jenny");
name: "John"
gender: "unspecified"
children: ["jack", "jenny"]
age: 45
name: "Jane"
age: 35
gender: "female"
children: ["jack", "jenny"]
What am I missing??
Like Konrad said in his comment, "arrays are also objects and are reference types".
The issue is that the spread operator (...) only goes on level deep, so for the array in extProps, is it not copied, it is the same one.
To solve this you can use a recursive function to "deep copy" an object.
Here is an example of a deep copy function:
const deepCopy = objIn => {
if (typeof objIn !== 'object' || objIn === null) return objIn;
let objOut = Array.isArray(objIn) ? [] : {};
for (const key in objIn) {
objOut[key] = deepCopy(objIn[key]);
}
return objOut;
}

Checking existence of object in Array in Javascript based on a particular value

I have an array of objects, and want to add a new object only if that object doesn't already exist in the array.
The objects in the array have 2 properties, name and imageURL and 2 objects are same only if their name is same, and thus I wish to compare only the name to check whether the object exists or not
How to implement this as a condition??
Since you've not mentioned the variables used. I'll assume 'arr' as the array and 'person' as the new object to be checked.
const arr = [{name: 'John', imageURL:'abc.com'},{name: 'Mike', imageURL:'xyz.com'}];
const person = {name: 'Jake', imageURL: 'hey.com'};
if (!arr.find(
element =>
element.name == person.name)
) {
arr.push(person);
};
If the names are not same, the person object won't be pushed into the array.
You can use Array.find
let newObj={ name:'X',imageURL:'..../'}
if(!array.find(x=> x.name == newObj.name))
array.push(newObj)
You need to check it using find or similar functions like this:
const arr = [{ name: 1 }, { name: 2 }];
function append(arr, newEl) {
if (!arr.find(el => el.name == newEl.name)) {
arr.push(newEl);
}
}
append(arr, { name: 2 }); // won't be added
console.log(arr);
append(arr, { name: 3 }); // will be added
console.log(arr);

Removing all objects that have a property/value duplicate BUT the last [duplicate]

This question already has answers here:
Javascript es6 - How to remove duplicates in an array of objects, except the last duplicate one?
(3 answers)
Closed 3 years ago.
I need to loop through an array of objects where each object will have an email property. My goal is to loop through the data (CSV) and if any record has the same email, I need to remove all but the last as that will be the value that I need to update in the end. I can't seem to get this right.
I have tried using .find but I never quite made it all the way. I feel like I need to add to it but I'm hazy as to what.
let arr = [
{name: 'stefano', email: 'stef#mail.com'},
{name: 'steve', email: 'cuck#mail.com'},
{name: 'weave', email: 'stef#mail.com'},
{name: 'peave', email: 'luck#mail.com'}
];
let keepLast = arr.find( (obj,idx) => {
let found = 0;
if(obj.email === 'stef#mail.com') {
++found;
}
if(found > 1) {
// Somehow remove the previous iteration catch on match
}
});
This is about where I am. I feel like I need to somehow keep memory of the last index so I know to remove it as soon as I find another one.
I'd reduce into an object indexed by the email, thereby overwriting the previous object at that email key if it exists. Then just take that object's values:
let arr = [
{name: 'stefano', email: 'stef#mail.com'},
{name: 'steve', email: 'cuck#mail.com'},
{name: 'weave', email: 'stef#mail.com'},
{name: 'peave', email: 'luck#mail.com'}
];
const output = Object.values(
arr.reduce((a, obj) => {
a[obj.email] = obj;
return a;
}, {})
);
console.log(output);

Iterating though object in array in React (ES6) [duplicate]

This question already has answers here:
How to iterate over a JavaScript object?
(19 answers)
Closed 5 years ago.
I have an object in array like the following:
bears: [
{
Yogi: "123kg",
Pooh: "110kg",
Grizly: "112kg",
BooBoo: "200kg",
Polar: "100kg",
}
]
`
What is the best way to iterate through such object in order to display both names and values in the row, like returning something in the type of: <p>${name} ${value}</p>
So I would display:
Yogi 123kg
Pooh 110kg
Grizly 112kg
BooBoo 200kg
Polar 100kh
It's an array containing an object, not an object. Anyway just get the first item of the array.
This should work:
Object.keys(bears[0]).map(key => <p>{`${key} ${bears[0][key]}`}</p>);
I think that the JSON object's structure itself is wrong.
It should be structured like this:
var bears = [{
name: "Yogi",
weight: "123kg"
}, {
name: "Pooh",
weight: "110kg"
}, {
name: "Grizly",
weight: "112kg"
}, {
name: "BooBoo",
weight: "200kg"
}]
Then you can go ahead and iterate through it using a for loop inside of the render() method like this.
render() {
var bearElements = [];
for (var bearIndex = 0; bearIndex < bears.length; bearIndex++) {
bearElements.push(
<p>{`${bears[bearElements].name}` `${bears[bearElements].weight}`}</p>
)
}
return (
<div>{bears}</div>
);
}

JavaScript: Dynamically generated object key [duplicate]

This question already has answers here:
Creating object with dynamic keys [duplicate]
(2 answers)
Closed 5 years ago.
const cars = [
{
'id': 'truck',
'defaultCategory': 'vehicle'
}
]
const output = []
Object.keys(cars).map((car) => {
output.push({
foo: cars[car].defaultCategory
})
})
console.log(output)
This work fine, however what I want to achieve is so that the newly crated object has structure of 'truck': 'vehicle'.
So if I replace push argument with
${cars[car].id}`: cars[car].defaultCategory
I get SyntaxError: Unexpected template string
What am I doing wrong?
Use map on the array, and not the keys (the indexes) to get an array of objects. For each object use computed property names to set the id value as the key:
const cars = [
{
'id': 'truck',
'defaultCategory': 'vehicle'
}
];
const result = cars.map(({ id, defaultCategory }) => ({ [id]: defaultCategory }));
console.log(result);
You should use .map() over your cars array and not Object.keys(cars):, we don't use Object.keys() with arrays.
This is how should be your code:
var output = cars.map(function(car) {
return {
[car.id]: car.defaultCategory
};
});
var cars = [{
'id': 'truck',
'defaultCategory': 'vehicle'
}];
var output = cars.map(function(car) {
return {
[car.id]: car.defaultCategory
};
});
console.log(output);

Categories