This question already has answers here:
Keyword 'const' does not make the value immutable. What does it mean?
(5 answers)
Const in JavaScript: when to use it and is it necessary?
(18 answers)
Closed 3 years ago.
let courses = [
{id:1, name : "Femin"},
{id:2, name : "Darsh"},
{id:3, name : "Smit"},
];
let enteredId = 2;
const course = courses.find(c => c.id === enteredId);
course.name = "Darsh Bhimani";
console.log(course);
console.log(courses);
So this is the code I've been working with.
I have been working with Java and C,C++ for the past 5-6 years and started with Javascript a week back. (For node.js).
Now what I am finding confusing here are two things:
The variable course is a constant, still its value can be changed. How ?
The course is fetched from the array courses, but still on changing course, when I log courses, I see that the value of the array has also changed. How is that possible?
In this case it does not matter if the value changes, but when I don't want the array to change, what can I do?
You get with find an object reference and to break this, you could get a shallow copy of the object with Object.assign. This approach works undefined as well, but returns in that case an empty object.
let courses = [
{id:1, name : "Femin"},
{id:2, name : "Darsh"},
{id:3, name : "Smit"},
];
let enteredId = 2;
const course = Object.assign({}, courses.find(c => c.id === enteredId));
course.name = "Darsh Bhimani";
console.log(course);
console.log(courses);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Related
This question already has an answer here:
JS : Convert Array of Strings to Array of Objects
(1 answer)
Closed 3 years ago.
I am trying to add id in a components array. id's will be incrementing based on the no. of components.
component_names = ['test1', 'test2'];
I want to create a new array components which will become :
components = [{id:1, name: 'test1'}, {id:2, name: 'test2'}]
// The ids will increment as the no. of components increase.
What I am trying:
let arr=[];
for(let i=0;i<component_names.length;i++){
arr.push({id:i+1, name: component_names[i]});
}
The above solution works but can I do the same with any of the higher order functions in javascript?
A simple map will work, where parameter 1 is the item and parameter 2 is the index.
let component_names = ['test1', 'test2']
let result = component_names.map((itm, idx) => ({id:++idx,name:itm}))
console.log(result)
let arr = component_names.map((name, index) => ({ name: name, id: index + 1 }));
This question already has answers here:
How to determine if Javascript array contains an object with an attribute that equals a given value?
(27 answers)
Closed 4 years ago.
I have an array with multiple objects inside.
It's structured like that:
const Instructor = [
{ ID: '141',
InstructorNameAR: 'test',
InstructorNameEN: 'Mohamed Ahmed',
InstructorBriefAR: 'phd in chemistry',
InstructorBriefEN: 'phd in chemistry' },
{ ID: '140',
InstructorNameAR: 'test',
InstructorNameEN: 'Mahmoud Ahmed',
InstructorBriefAR: 'phd in chemistry',
InstructorBriefEN: 'phd in chemistry' },
]
I wanted to add other objects but filtered of duplicates based on their ID values.
Example of objects i want to add :-
const InstructorInstance = {
ID: 'ID',
InstructorNameAR: 'NAMEAR',
InstructorNameEN: 'NAMEEN',
InstructorBriefAR: 'BRIEFAR',
InstructorBriefEN : 'BRIEFEN'
}
I used this method to filter by ID.
But it didn't work as it compares only a single value of the array to the value i provided. which means it might be a duplicated object but still gets added because it did not check if it exists in each array element
Instructor.forEach(instance =>{
if(instance.ID !== InstructorInstance.ID){
Instructor.push(InstructorInstance);
}else{
console.log('Duplicate')
}
})
You have to loop the whole array first before deciding whether there is a duplicate or not. You can use forEach for that but every or some seem like the perfect fit for this kind of job:
const test = Instructor.every(instance => instance.ID !== InstructorInstance.ID);
if(test) {
Instructor.push(InstructorInstance);
}
Which means if every object in Instructor has a different ID than InstructorInstance, then push InstructorInstance into Instructor.
Note: You can put the test directly inside if without having to store it in a variable test:
if(Instructor.every(instance => instance.ID !== InstructorInstance.ID)) {
Instructor.push(InstructorInstance);
}
But that doesn't look, does it?
You can use some to check if that object already exists, if not, add it:
if (!Instructor.some(i => i.ID == instance.ID)) {
Instructor.push(instance);
}
This question already has answers here:
javascript filter array of objects
(8 answers)
Closed 4 years ago.
This is the issue Im trying to solve. I know how to do direct comparison with objects, but Im caught how to make an either or property comparison inside a filter fx.
// tasks are objs with {name: string,id: int}
const taskArray = [task1, task2, task3, task3];
// f(x) needs to take obj param and see if it matches either/or with
// any task obj k/v pair
// my implementation so far, missing something important, help here
const filterTasks = (taskArray, obj) => {
taskArray.filter( task => Object.keys(task) // i know I have to do some equality opperator here but stuck
return taskArray;
}
There it is.
filterTasks will return an array that contains only tasks in the passed array that match at least 1 key/val pair in the passed object.
tArr = [{name: "hi",id: 1},{name: "hola",id: 2},{name: "hello",id: 3},{name: "bye",id: 4}];
const filterTasks = (taskArray, obj) => taskArray.filter( task => Object.keys(task).some( key => obj[key] && obj[key]==task[key]));
console.log(filterTasks(tArr,{name:"hi",id:2}));
This question already has answers here:
Does JavaScript guarantee object property order?
(13 answers)
Closed 4 years ago.
Within the example script I have generated two arrays I would like to combine to a single row:
var testHeaders = ["aLabel", "bLabel", "cLabel","dLabel","eLabel"];
and
var testValue = ["aValue","bValue", "cValue","dValue","eValue"];
What I am trying to achieve is a string like { aLabel = aValue, bLabel = bValue, ... } that can be used to upload into BigQuery (the data upload job works).
I found a piece of code that almost does this, but somehow it changes the order of the elements within the two arrays.
var code = testValue.reduce(function(obj, value, index) {
obj[testHeaders[index]] = value;
return obj
}, {})
However, the result does mix up the order of the arrays as seen below. I am not capable of figuring out why the order changes. As far as I know, reduce() should work its way from left to right in an array.
The returned object is:
{
aLabel = aValue,
dLabel = dValue,
bLabel = bValue,
eLabel = eValue,
cLabel = cValue
}
You can use map and join:
var testHeaders = ["aLabel", "bLabel", "cLabel","dLabel","eLabel"];
var testValue = ["aValue","bValue", "cValue","dValue","eValue"];
var res = '{' + testHeaders.map((label, i) => `${label}=${testValue[i]}`).join(',') + '}';
console.log(res);
As vlaz pointed out, you are creating neither a string or a new array, but an object. And just like maps, objects do not have a set order of keys in JavaScript. hence, there is quite a chance of getting another order in the object than in both arrays.
This question already has answers here:
How do I find an array item with TypeScript? (a modern, easier way)
(5 answers)
Closed 5 years ago.
So my question how can I check this array of objects by "key" for eg I want to check if the key 3892 is there, I have tried with indexOf but no luck, I can't use a loop.
You can use some() and hasOwnProperty()
var array = [{3892: 'value'}, {1234: 'value'}];
var check = array.some(obj => obj.hasOwnProperty(3892));
console.log(check)
You can chain Object.keys with Array.prototype.includes to achieve that
Object.keys(myObject).includes(myKey);
const myObject = { name: 'Peter' };
const myKey = 'name';
const result = Object.keys(myObject).includes(myKey);
console.log(`Includes key ${myKey}? `, result);