How Can I Change Constant Array in Javascript? - javascript

I have an array data but it declared with const. I am rather confused to change the data in array. Here is my array:
const person = {
name: "Person A", ---> the data I want to change
age: 100,
favDrinks: [
"coffee",
"temulawak", --->> the data I want to change
"tea"
],
greeting: function() {
console.log("Hello World"); --->> the data I want to change
}
}
How can I change the data of person.name, person.favDrinks[1], and greeting function of "Hello World". Is there a possible way to change constant data? I want to change to text strings. Here is my code :
function personName(nama ){
let person.name = nama;
person.push("name:" nama );
}
console.log(personName("Molly"));
But they are all wrong. Please help me. Thank you. :)

You are doing a couple of things wrong.
You are pushing into an object, instead of an array.
You are redefining the object person by using let inside your function.
You can change properties of a const object; however, you cannot reassign it.
Simply add return person
const person = {
name: "Person A",
age: 100,
favDrinks: ["coffee", "temulawak", "tea"],
greeting: function () {
console.log("Hello World");
},
};
function personName(nama) {
person.name = nama;
return person;
}
console.log(personName("Molly"));
This is what you'll get after your changes have been made:
{
name: 'Molly',
age: 100,
favDrinks: [ 'coffee', 'temulawak', 'tea' ],
greeting: [Function: greeting]
}

You are using let to create a variable with the name person.name which is not possible and then pushing it into person, in your case this is not what you should do, instead just change the values directly.
function personName(nama) {
person.name = name
return person
}
console.log(personName("Molly"));
if a constant variable is a string or a jumber, it cannot be changed. but if it is an array or object it cannot be changed but items in the object or array can be added, removed, or edited.

person is an object, not an array.
You can change properties values of a constant object.
Working Demo :
const person = {
name: "Person A",
age: 100,
favDrinks: [
"coffee",
"temulawak",
"tea"
],
greeting: function() {
console.log("Hello World");
}
};
person.name = "Person B";
person.favDrinks[1] = "Soft Drinks";
person.greeting = function() {
console.log('Hello Guys!');
}
console.log('updated object', person);

I am following " Learn javascript " on Scrimba and I got into a weird situation.
I learned that const variables can not be reassigned and there are methods in arrays and objects where you can add or remove elements from them (e.g arr.push())
const s = [5, 7, 2];
function editInPlace() {
"use strict";
s = [2, 5, 7];
}
editInPlace();
Console error:
Error: SyntaxError: unknown: "s" is read-only (/index.js:1)
But here comes the magic, when they assigned the const array variables new values with specific indexes then it worked well.
const s = [5, 7, 2];
function editInPlace() {
"use strict";
//s = [2, 5, 7];
s[0] = 2;
s[1] = 5;
s[2] = 7;
}
editInPlace();
console.log(s)
Console output:
[2, 5, 7]
Now I am not able to understand why is this happening.
Looking forward to listen from you.

Related

Javascript Object manipulation to create an Object list with a variable id

I am not comfortable with certain subtleties, and here are 2 days that I go around in circles, to carry out "manipulations" of Objects in javascript (NodeJS), I therefore appeal to your knowledge!
I send elements from a json as a parameter in a .js script.
in this script, I would like to process the elements sent as a parameter (by a loop), to add them to a list, then to be able to add others "manually", to finally get a "list" of the set with different additional information.
my "test" script where I simulate the parameters received and "try" to get this "list":
let params = JSON.parse('{ "100": 3, "101": 1 }') // simulate parameters
let lstObj = {} // content all the list obj
// only for the test
function foo(type) {
return "type is " + type;
}
function addToList(id, type) {
let obj = {
id: id,
type: type,
test: foo(type)
}
console.log('from addToList() -> ', obj);
return obj;
}
// process the Obj from parameters
let index = 0;
for (let [key, value] of Object.entries(params)) {
console.log("from Param: ", `${key} -> ${value}`, " or ", key, "->", value);
obj = addToList(key, value); // seem work
//lstObj.key = obj; // use 'key' not the key value
//lstObj.[key] = obj; // error
//lstObj.`${key}` = obj; // error
//lstObj.["999"] = obj; // error
//index++; lstObj.index = obj; // bad :)
lstObj.a999 = obj; // Work ! but how can a make it ?
}
console.log('\nResult -> ', lstObj);
// Now want to manualy add other Obj in the List, like this ?
// lstObj.999 = addToList("999", 3)
I would like to get a result like this:
{
"100": {id: 100, type: 1, test: 'Type is 1', ....}
"102": {id: 102, type: 3, test: 'Type is 3', ....}
"110": {id: 110, type: 1, test: 'Type is 1', ....}
"305": {id: 305, type: 2, test: 'Type is 2', ....}
}
The purpose of being able to subsequently retrieve the object of an element by a call like: "lstobj.101"
Thank's a lot !
What you need is to assign the key to the object.
Change this line
lstObj.a999 = obj; // Work ! but how can a make it ?
to
lstObj[key] = obj;
What this does is assign whatever value is contained by variable key to be a key in variable lstObj, then assign the value of obj as it's value.
For example
let key = 'exampleKey';
let value = 'exampleValue';
let obj = {};
obj[key]=value; //now object is { 'exampleKey': 'exampleValue' }

Turf JS does not create Object properly

I am using the helper function turf.point()
const feature = turfHelpers.point(coords, properties, { id: properties.id });
properties looks like this
properties = {
id: 1,
thisWorks: 'no problem'
foo: {
thisDoesntWork: 'this is a problem'
}
}
When I create feature with turfHelpers.point(), it messes with the object. The nested object is not an object anymore, but gets stringyfied...
So, features.properties is
{
id: 1,
thisWorks: 'no problem'
foo: "{
thisDoesntWork: 'this is a problem'
}"
}
Now, I cannot access. feature.properties.foo.thisDoesntWork anymore, because its a string...
Why is turf.js doing that?
Let's put the question in the runnable form.
const turfHelpers = turf.helpers;
const coords = [100, 14];
const properties = {
id: 1,
thisWorks: 'no problem',
foo: {
thisDoesntWork: 'this is a problem'
}
};
var feature1 = turfHelpers.point(coords, properties, {
id: properties.id
});
// Print out on console
console.log(feature1.properties); //look OK
console.log(feature1.properties.foo); //also OK
console.log(feature1.properties.foo.thisDoesntWork); //also OK
<script src="https://cdnjs.cloudflare.com/ajax/libs/Turf.js/5.1.5/turf.min.js"></script>
Then, hopefully, it is helpful for discussion that leads to a solution.

Creating a JavaScript function that filters out duplicate in-memory objects?

Okay, so I am trying to create a function that allows you to input an array of Objects and it will return an array that removed any duplicate objects that reference the same object in memory. There can be objects with the same properties, but they must be different in-memory objects. I know that objects are stored by reference in JS and this is what I have so far:
const unique = array => {
let set = new Set();
return array.map((v, index) => {
if(set.has(v.id)) {
return false
} else {
set.add(v.id);
return index;
}
}).filter(e=>e).map(e=>array[e]);
}
Any advice is appreciated, I am trying to make this with a very efficient Big-O. Cheers!
EDIT: So many awesome responses. Right now when I run the script with arbitrary object properties (similar to the answers) and I get an empty array. I am still trying to wrap my head around filtering everything out but on for objects that are referenced in memory. I am not positive how JS handles objects with the same exact key/values. Thanks again!
Simple Set will do the trick
let a = {'a':1}
let b = {'a': 1,'b': 2, }
let c = {'a':1}
let arr = [a,b,c,a,a,b,b,c];
function filterSameMemoryObject(input){
return new Set([...input])
}
console.log(...filterSameMemoryObject(arr))
I don't think you need so much of code as you're just comparing memory references you can use === --> equality and sameness .
let a = {'a':1}
console.log(a === a ) // return true for same reference
console.log( {} === {}) // return false for not same reference
I don't see a good reason to do this map-filter-map combination. You can use only filter right away:
const unique = array => {
const set = new Set();
return array.filter(v => {
if (set.has(v.id)) {
return false
} else {
set.add(v.id);
return true;
}
});
};
Also if your array contains the objects that you want to compare by reference, not by their .id, you don't even need to the filtering yourself. You could just write:
const unique = array => Array.from(new Set(array));
The idea of using a Set is nice, but a Map will work even better as then you can do it all in the constructor callback:
const unique = array => [...new Map(array.map(v => [v.id, v])).values()]
// Demo:
var data = [
{ id: 1, name: "obj1" },
{ id: 3, name: "obj3" },
{ id: 1, name: "obj1" }, // dupe
{ id: 2, name: "obj2" },
{ id: 3, name: "obj3" }, // another dupe
];
console.log(unique(data));
Addendum
You speak of items that reference the same object in memory. Such a thing does not happen when your array is initialised as a plain literal, but if you assign the same object to several array entries, then you get duplicate references, like so:
const obj = { id: 1, name: "" };
const data = [obj, obj];
This is not the same thing as:
const data = [{ id: 1, name: "" }, { id: 1, name: "" }];
In the second version you have two different references in your array.
I have assumed that you want to "catch" such duplicates as well. If you only consider duplicate what is presented in the first version (shared references), then this was asked before.

How to read an immutable record which is inside immutable list?

I could read the immutable list and immutable record independently. But I have an immutable record which is nested inside immutable list which I am not able to read.
Immutable List:
let listObj = Immutable.List([{a:'0', b:'1'}, {c:'2', d:'3'}])
console.log('listObj', listObj._tail.array[0]); // {a:'0', b:'1'}
Immutable Record:
const Person = Immutable.Record({
name: null
}, 'Person')
let me = Person({ name: 'Steve' })
me.toString() // "Person { "name": "My Name" }"
let myName = me.get('name')
console.log('myName', myName) // "Steve"
Immutable Record inside Immutable List:
let x = Immutable.List([Immutable.Record({
name: 'Steve'
})])
console.log('x', x) // undefined
Can you please give some pointers, if any, to understand how to read an immutable record which is nested inside an immutable list?
Thanks!
If you try actually running your code:
let x = Immutable.List([Immutable.Record({
name: 'Steve'
})])
console.log('x', x) // Spoiler alert: NOT undefined
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.2/immutable.js"></script>
You'll find that it outputs
x List [ function Record(values) {
...
} ]
Notice how the thing in the list is a function? That's because it's a Record.Factory, not actually a Record itself. You need to use it like you do in your second example where you create a Record.Factory and then use to create a Record:
const Person = Immutable.Record({
name: null
}, 'Person')
let me = Person({
name: 'Steve'
})
let x = Immutable.List([me])
console.log(x) // [{"name": "Steve"}]
console.log(x.get(0)) // {"name": "Steve"}
console.log(x.getIn([0, 'name'])) // "Steve"
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.2/immutable.js"></script>

How to push an object in an Array?

Iam trying to push in array an object, but I get always error.
fCElements = [],
obj = {};
obj.fun = myFunction;
obj.id = 2;
fCElements.push ({
obj,
myid:2,
name:'klaus'
})
how I can push into array functions like "myFunction"?
Thanks
In the Object literal, you can only give key-value pairs. Your obj doesn't have any value.
Instead, you can do like this
var fCElements = [];
fCElements.push({
obj: {
fun: myFunction,
id: 2
},
myid: 2,
name: 'klaus'
});
Now, you are creating a new object, obj, on the fly, while pushing to the array. Now, your fCElements look like this
[ { obj: { fun: [Function], id: 2 }, myid: 2, name: 'klaus' } ]
You need to give your obj property a name (or a value).
var obj = {};
obj.fun = myFunction;
obj.id = 2;
fCElements.push ({
obj:obj,
myid:2,
name:'klaus'
});
The object you are pushing to the array seems off. It will try to push this object:
{
{fun: myfunction, id: 2},
myid: 2,
name: 'klaus'
}
Which is an invalid object since the first value has no key. You should do it like this instead:
fCElements.push ({
myObj:obj,
myid:2,
name:'klaus'
});

Categories