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)
Array.includes() to find object in array [duplicate]
(8 answers)
Javascript: Using `.includes` to find if an array of objects contains a specific object
(7 answers)
Closed 7 months ago.
Trying to add new object value in an array but not working. How to add it? If anyone knows please help to find the solution.
getting this error:
Property 'includes' does not exist on type '{ name: string; id:
string; }[]'. Do you need to change your target library? Try changing
the 'lib' compiler option to 'es2016' or later.
app.component.ts:
public a = { name: 'test1', id: '12345' };
public b = { name: 'test2', id: '12345' };
addVala() {
if (this.arr.includes(this.a)) {
console.log('This obj already there');
} else {
this.arr.push(this.a);
}
console.log(this.arr);
}
Demo : https://stackblitz.com/edit/angular-ivy-jj7sna?file=src%2Fapp%2Fapp.component.ts,src%2Fapp%2Fapp.component.ts
You can simplify your "add" logic by passing-in the object that you want to add and checking if another object (already in the list) shares the same ID.
const arr = [
{ name: 'test1', id: 'A' },
{ name: 'test3', id: 'C' },
];
const a = { name: 'test1', id: 'A' };
const b = { name: 'test2', id: 'B' };
const add = (obj) => {
if (!arr.find(({ id }) => id === obj.id)) {
arr.push(obj);
console.log(`Added ${obj.id}`);
} else {
console.log(`Object ${obj.id} already exists!`);
}
}
function addA() { add(a); }
function addB() { add(b); }
<button onclick="addA()">Add A</button>
<button onclick="addB()">Add B</button>
Related
This question already has answers here:
How to add same elements to javascript array n times
(4 answers)
Weird behavior with objects & console.log [duplicate]
(2 answers)
Closed 3 years ago.
const get = function() {
return {
name: 'me'
}
}
const array = Array(10).fill(get());
console.log(array);
array.map(item => {
console.log('1', item);
item.a = '555'
console.log('2', item);
return item;
})
As you see, I modify element in the array like this item.a = '555'. I might console.log will output like this:
1 { name: 'me' }
2 { name: 'me', a: '555' }
but, actually I got this:
1 { name: 'me', a: '555' }
2 { name: 'me', a: '555' }
How to understand this?
This question already has answers here:
Destructuring deep properties
(4 answers)
Closed 4 years ago.
I have this object
const storeObj = {
name: {
firstName: 'abc'
}
}
I can do alias by assigning name to username
const { name: username } = storeObj
I can do nested destructuring like so
const { name: { firstName } } = storeObj
Can I use them both together? I want to achieve one line when aliasing aka renanming and nested destructuring.
Yes, just put those two together - when you want to assign to a different variable name than the property name, put the new variable name after a colon. This works regardless of the level of the nested object.
const storeObj = {
name: {
firstName: 'abc'
}
}
const { name: { firstName: username } } = storeObj;
console.log(username);
This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Creating object with dynamic keys [duplicate]
(2 answers)
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Is it possible to add dynamically named properties to JavaScript object?
(20 answers)
Closed 4 years ago.
nameChangedHandler = (id, event) => {
let index = id;
const updatedName = event.target.value;
this.setState({
persons: update(this.state.persons, { index: { name: { $set: updatedName } } }),
});
};
If I hardcode the index to any number the above code is working i.e ( update(this.state.persons, { 0: { name: { $set: updatedName } } }) )
Kindly Suggest a Solution.
replace { index: ... } with { [index]: ... }
You can use a computed property to use the value of the index variable:
this.setState({
persons: update(this.state.persons, { [index]: { name: { $set: updatedName } } }),
});
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);
This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 5 years ago.
This may be a really daft question or an impossible question..
I have a table which uses two arrays of objects like so:
const columnData = [
{ id: 'name', label: 'Name' },
{ id: 'value', label: 'Value' }
];
const rowData = [
{ name: 'Name 01', value: 100 },
{ name: 'Name 02', value: 150 },
{ name: 'Name 03', value: 200 },
];
I am writing this as a separate react component so I can reuse it and just change the two sets of data passed in as props. This is all fine and working, however I am struggling to figure out how to map the rows and columns to be dynamic.
i.e.:
...
{this.props.rowData.map(row => {
return (
<tr>
{this.props.columnData.map(column => {
return (
<td>{row.(THE_COLUMN_ID_TO_GET_THE_VALUE)}</td>
);
}
</tr>
);
}
...
I hope I make some sense here as it's a bit vague.. I basically want to get the value from rowData using the column id name. EG: <td>{row.name}</td><td>{row.value}</td> without hardcoding the item.
You can use the [] syntax on objects to obtain values based on computed properties.
{this.props.rowData.map(row => {
return (
<tr>
{this.props.columnData.map(column => {
return (
<td>{row[column.id]}</td>
);
}
</tr>
);
}
So you just want to get the property of the row that matches the column id? You can access a property with dynamic name using square brackets like row[column.id]
{this.props.rowData.map(row => {
return (
<tr>
{this.props.columnData.map(column => {
return (
<td>{row[column.id]}</td>
);
}
</tr>
);
}