Unexpected effect: Making a copy of an object modifies it - javascript

Context:
I have a component whichj emits data to the parent. Parent has two default objects-An empty array, and another object which contains default values, which are used to add a new element to the array using the data passed.
Template:
<billing-search
:search-term="searchText"
:show-modal="showBillingModal"
#closeModal="CloseBillingModal"
#selectedAnItem="AddSelectedItem"
/>
Initial data:
data() {
return {
billitems: [],
billitem_def: {
invitem: null,
procitem: null,
stockid: null,
qty: 0,
unitprice: 0,
discpercent: 0,
disc: 0,
}
}
},
My method in the parent triggered on emiting from the component, is this:
AddSelectedItem(data) {
console.log(`In AddSelectedItem`);
console.log(`this.billitems was `, this.billitems);
console.log(`Got data passed by component:`, data);
let newitem = this.billitem_def
console.log(`this.billitems was `, this.billitems);
newitem.invitem = data.item
newitem.stockid = data.storeitem
newitem.unitprice = newitem.stockid.mrp
console.log(`Added new item to billing list:`);
console.log(newitem);
this.billitems.push(newitem)
console.log(`this.billitems is now `, this.billitems);
console.log(`this.billitem_def is `, this.billitem_def);
},
See an example of console log:
In AddSelectedItem
BillingBlock.vue?670b:173 this.billitems was
0:
disc: 0
discpercent: 0
invitem: {id: 50, name: 'Waxonil Activ Ear Drops', description: 'Adult ear drops', itemtype: 4, clinic: 10, …}
procitem: null
qty: 0
stockid: {id: 432, entry: {…}, item: {…}, quantity: 30, stock: 21, …}
unitprice: "119.30"
BillingBlock.vue?670b:174 Got data passed by component:
{
item: {
clinic: 10
description: "Adult ear drops"
drugid: null
id: 50
isOpen: true
itemtype: 4
name: "Waxonil Activ Ear Drops"
storeitem: (13) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
},
storeitem: {
batchnum: "SW135"
entry: {id: 275, entry_number: 'WjazQPLxb', reference_number: '', invoice_number: 'A-50864', entry_date: '2021-12-20', …}
expirydate: "2024-08-21"
id: 432
item: {id: 50, name: 'Waxonil Activ Ear Drops', description: 'Adult ear drops', itemtype: 4, clinic: 10, …}
manufacturedate: null
}
}
BillingBlock.vue?670b:177 this.billitems was
Proxy {
0:
disc: 0
discpercent: 0
invitem: {id: 50, name: 'Waxonil Activ Ear Drops', description: 'Adult ear drops', itemtype: 4, clinic: 10, …}
procitem: null
qty: 0
stockid: {id: 432, entry: {…}, item: {…}, quantity: 30, stock: 21, …}
unitprice: "119.30"
}
BillingBlock.vue?670b:181 Added new item to billing list:
BillingBlock.vue?670b:182
Proxy {invitem: {…}, procitem: null, stockid: {…}, qty: 0, unitprice: '119.30', …}
BillingBlock.vue?670b:185 this.billitems is now
Proxy {0: {…}}
BillingBlock.vue?670b:186 this.billitem_def is
Proxy { invitem: {… }, procitem: null, stockid: {… }, qty: 0, unitprice: '119.30', … }
Problems with this:
The this.billitems was shows data even before it is being assigned, instead of an empty array
this.billitem_def was set to some null values initially in the data part. It was not meant to get values, but to serve as a template of default data. Though I had let newitem = this.billitem_def, how is this.billitem_def's data getting modified? I dont have code anywhere in the project assigning this.billitem_def to anything else.

Related

Accessing objects inside arrays

My API is returning the below response. I am trying to filter through the links to check if the source and target name properties in each object match a specific string. Any idea how I can do this, I am have troubling getting to the name property.
Currently this.chart.links.target.name and this.chart.links.source.name are returning undefined. I cannot seem to access the name properties.
Proxy {nodes: Array(69), links: Array(68)}
[[Handler]]: Object
[[Target]]: Object
links: Array(68)
0:
circular: false
index: 0
real_value: 10
source: {name: 'String1', color: 'yellow', index: 30, sourceLinks: Array(30), targetLinks: Array(24), …}
target: {name: 'String2', color: 'red', index: 0, sourceLinks: Array(0), targetLinks: Array(1), …}
value: 10
width: 2.152297042164877
y0: 111.36731918963686
y1: 193.80113278791737
[[Prototype]]: Object
1: {source: {…}, target: {…}, value: 10, real_value: 10, index: 1, …}
2: {source: {…}, target: {…}, value: 10, real_value: 10, index: 2, …}
3: {source: {…}, target: {…}, value: 10, real_value: 10, index: 3, …}
4: {source: {…}, target: {…}, value: 10, real_value: 10, index: 4, …}
5: {source: {…}, target: {…}, value: 10, real_value: 10, index: 5, …}
6: {source: {…}, target: {…}, value: 10, real_value: 10, index: 6, …}
7: {source: {…}, target: {…}, value: 10, real_value: 10, index: 7, …}
this is how my filter is looking:
const dataToFilter = ['String1', 'String2']
const links = this.chart.links.filter(io =>
!dataToFilter.includes(io.source.name || io.target.name)
)
Instead of !dataToFilter.includes(io.source.name || io.target.name) you want to have !(dataToFilter.includes(io.source.name) || dataToFilter.includes(io.target.name)) to check against the names separately.

How to return an array of unique objects based on the id of the object in es6?

Array(96) [ {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, … ]
​
0: Object { id: 1, name: "PrimShal01", period: 3, … }
1: Object { id: 61, name: "TertDeep01", period: 1, … }
2: Object { id: 37, name: "SecoDeep01", period: 2, … }
3: Object { id: 49, name: "TertShal01", period: 1, … } ​
4: Object { id: 13, name: "PrimDeep01", period: 3, … }
5: Object { id: 61, name: "TertDeep01", period: 1, … }
When I try the following code I only get the unique id, but I want the objects:
const uniques = [new Set(all_filter_ids.map(pos => pos.id))]
When I try the following code I get the the same as before:
const uniques = [new Set(all_filter_ids)]
Turn them into a Map indexed by ID (only one object can exist for a key), then turn the Map's values back into the array.
const map = new Map(all_filter_ids.map(pos => [pos.id, pos]));
const uniques = [...map.values()];
Another one solution:
const arr = [{ id: 1, name: "PrimShal01", period: 3},{ id: 61, name: "TertDeep01", period: 1},{ id: 37, name: "SecoDeep01", period: 2},{ id: 49, name: "TertShal01", period: 1},{ id: 13, name: "PrimDeep01", period: 3},{ id: 61, name: "TertDeep01", period: 1}]
const result = Object.values(
arr.reduce((acc, obj) => ({ ...acc, [obj.id]: obj }), {})
);
console.log(result);
.as-console-wrapper{min-height: 100%!important; top: 0}
Maintain a set for tracking id's and use filter
const uniq = (arr, track = new Set()) =>
arr.filter(({ id }) => (track.has(id) ? false : track.add(id)));
const arr = [
{ id: 1, name: "PrimShal01", period: 3 },
{ id: 61, name: "TertDeep01", period: 1 },
{ id: 37, name: "SecoDeep01", period: 2 },
{ id: 49, name: "TertShal01", period: 1 },
{ id: 13, name: "PrimDeep01", period: 3 },
{ id: 61, name: "TertDeep01", period: 1 },
];
console.log(uniq(arr))

Push adds array to array instead of elements [duplicate]

This question already has answers here:
Merge 2 arrays of objects
(46 answers)
Closed 1 year ago.
I need to get some data from API and store it in array. If I set value to it as assigning through = the returned data is displayed as I need. But if I use push to add elements they are added as another array.
It is console log of array after first assigning this.elements = response.data
Proxy {0: {…}, 1: {…}, 2: {…}}
[[Handler]]: Object
[[Target]]: Array(3)
0: {ID: 40, created_at: "2021-03-13T22:15:09.769066+03:00", updated_at: "2021-03-13T22:15:09.769066+03:00", DeletedAt: null, user_id: 19, …}
1: {ID: 39, created_at: "2021-03-13T22:15:06.779473+03:00", updated_at: "2021-03-13T22:15:06.779473+03:00", DeletedAt: null, user_id: 19, …}
2: {ID: 38, created_at: "2021-03-13T22:15:01.738319+03:00", updated_at: "2021-03-13T22:15:01.738319+03:00", DeletedAt: null, user_id: 19, …}
length: 3
__proto__: Array(0)
[[IsRevoked]]: false
And it is through push method this.elements .push(response.data)
Proxy {0: {…}, 1: {…}, 2: {…}, 3: Array(3)}
[[Handler]]: Object
[[Target]]: Array(4)
0: {ID: 40, created_at: "2021-03-13T22:15:09.769066+03:00", updated_at: "2021-03-13T22:15:09.769066+03:00", DeletedAt: null, user_id: 19, …}
1: {ID: 39, created_at: "2021-03-13T22:15:06.779473+03:00", updated_at: "2021-03-13T22:15:06.779473+03:00", DeletedAt: null, user_id: 19, …}
2: {ID: 38, created_at: "2021-03-13T22:15:01.738319+03:00", updated_at: "2021-03-13T22:15:01.738319+03:00", DeletedAt: null, user_id: 19, …}
3: Array(3)
0: {ID: 38, created_at: "2021-03-13T22:15:01.738319+03:00", updated_at: "2021-03-13T22:15:01.738319+03:00", DeletedAt: null, user_id: 19, …}
1: {ID: 33, created_at: "2021-03-13T10:59:06.521453+03:00", updated_at: "2021-03-13T10:59:06.521453+03:00", DeletedAt: null, user_id: 19, …}
2: {ID: 32, created_at: "2021-03-13T10:58:59.111903+03:00", updated_at: "2021-03-13T10:58:59.111903+03:00", DeletedAt: null, user_id: 19, …}
length: 3
__proto__: Array(0)
length: 4
__proto__: Array(0)
[[IsRevoked]]: false
How can I add elements of the array instead of the array itself?
You can use push with spread operator:
this.elements.push(...response.data)
E.g.
const arr1 = [1, 2, 3];
const arr2 = [12, 13, 14];
arr1.push(...arr2);
console.log(arr1);
You could use spread operator to concatenate the original array with the new one :
this.elements =[...this.elements, ...response.data]

Not displaying data from console.log

I'm working on a project in react, which I console.log a data and it shows, but when i try to display, its not working. I think im missing something. Its not displaying the length, id or body of the content
<Badge count={`${notify !== null ? notify.length : 0}`} overflowCount={10}>
<Dropdown
overlay={<Menu>
{notify && notify.map(notify => {
return (
<Menu.Item key={notify.id}>
{notify.body}
</Menu.Item>
);
})}
{notify && notify.length < 1 ? (
<Menu.Item>No notifications yet</Menu.Item>
) : null }
<Menu.Divider />
<Menu.Item onClick={() =>
this.props.history.push("/notifications")
}>
VIEW ALL <ArrowRightOutlined /></Menu.Item>
</Menu>
}
trigger={['click']}>
<a className="ant-dropdown-link" onClick={e => e.preventDefault()}>
<BellOutlined style={{ fontSize: '25px', color: '#2aa515' }}/>
</a>
</Dropdown>
</Badge>
This is the data from the console.log
(21) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
0:
assigned_to: 4
body: "tayodami followed you! ID: 12"
creation_date: "2020-10-10T19:41:23.428773Z"
group: "NF"
id: 21
is_read: true
pk_relation: 12
__proto__: Object
1: {id: 22, group: "NF", creation_date: "2020-10-10T19:43:27.537867Z", is_read: true, body: "que followed you! ID: 13", …}
2: {id: 23, group: "NF", creation_date: "2020-10-10T20:05:06.098263Z", is_read: true, body: "oladeji followed you! ID: 14", …}
3: {id: 24, group: "NF", creation_date: "2020-10-11T05:41:46.792794Z", is_read: true, body: "oladeji followed you!", …}
4: {id: 25, group: "NC", creation_date: "2020-10-11T10:39:02.069264Z", is_read: true, body: "que commented: asfasf.", …}
5: {id: 26, group: "NC", creation_date: "2020-10-11T10:40:26.915029Z", is_read: true, body: "que commented: asfasf.", …}
6: {id: 28, group: "NC", creation_date: "2020-10-11T11:36:50.180718Z", is_read: true, body: "que commented: hi.", …}
7: {id: 29, group: "NC", creation_date: "2020-10-11T11:45:38.079017Z", is_read: true, body: "que commented: gg on your post.", …}
8: {id: 31, group: "NC", creation_date: "2020-10-12T11:46:50.121499Z", is_read: true, body: "que commented: hi on your post.", …}
9: {id: 32, group: "NC", creation_date: "2020-10-12T11:50:42.081770Z", is_read: true, body: "que commented: "TODAY" on your pop.", …}
...
length: 21
__proto__: Array(0)
Use console.dir() instead of .log() to get all fields.
https://developer.mozilla.org/en-US/docs/Web/API/Console/dir

cannot change scope property

im trying to change an property value into the $scope variable of angular js, but the applied changes has not been setted.
my code is this:
in my code i have an costBudget with many childs into an array, and i need to reeplace these child for the costWorkPackages array.
let costBudget = $scope.list[0];
costBudget.subCostsWorkPackages = costsWorkPackages;
console.log(costBudget);
the costBudget variable is the same before and after to assign the new array, and its wrong. I expect the costBudget has the new childs, but does not happens.
UPDATED:
added console objects:
before the change:
{code: 1, internalId: 0, notRealWorkPackage: true, name: "shrh",
count: 1, …}
$$hashKey: "object:190"
code: 1
subCostsWorkPackages: Array(3)
0: Resource {id: 6491, name: "ascasca", count: 1,
subCostsWorkPackages: Array(0), resourceInstances: Array(0), …}
1: Resource {id: 6492, name: "ascasca", count: 1,
subCostsWorkPackages: Array(0), resourceInstances: Array(0), …}
2: Resource {id: 6493, name: "ascasca", count: 1,
subCostsWorkPackages: Array(0), resourceInstances: Array(0), …}
$promise: Promise {$$state: {…}}
$resolved: true
length: 3
__proto__: Array(0)
subNodeClass: ""
title: "shrh"
toggleButtonClass: "fa-minus-square-o"
__proto__: Object
after:
{code: 1, internalId: 0, notRealWorkPackage: true, name: "shrh",
count: 1, …}
$$hashKey: "object:190"
code: 1
subCostsWorkPackages: Array(3)
0: Resource {id: 6491, name: "ascasca", count: 1, subCostsWorkPackages: Array(0), resourceInstances: Array(0), …}
1: Resource {id: 6492, name: "ascasca", count: 1, subCostsWorkPackages: Array(0), resourceInstances: Array(0), …}
2: Resource {id: 6493, name: "ascasca", count: 1, subCostsWorkPackages: Array(0), resourceInstances: Array(0), …}
$promise: Promise {$$state: {…}}
$resolved: true
length: 3
__proto__: Array(0)
subNodeClass: ""
title: "shrh"
toggleButtonClass: "fa-minus-square-o"
__proto__: Object
UPDATE 2:
costsWorkPackage variable in console:
[Resource, Resource, Resource, Resource, $promise: Promise, $resolved:
true]
0: Resource {id: 6430, name: "Nombre 2", count: "1.00000000",
subCostsWorkPackages: Array(0), resourceInstances: Array(0), …}
1: Resource {id: 6437, name: "Nombre 9", count: "1.00000000",
subCostsWorkPackages: Array(0), resourceInstances: Array(0), …}
2: Resource {id: 6438, name: "Nombre 3", count: "1.00000000",
subCostsWorkPackages: Array(5), resourceInstances: Array(2), …}
3: Resource {id: 6431, name: "Nombre 3", count: "1.00000000",
subCostsWorkPackages: Array(5), resourceInstances: Array(2), …}
$promise: Promise {$$state: {…}}
$resolved: true
length: 4
__proto__: Array(0)

Categories

Resources