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?
Related
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>
This question already has answers here:
How do I convert array of Objects into one Object in JavaScript?
(17 answers)
Convert Javascript array of objects into one object
(4 answers)
How to convert array of objects in one specific object?
(9 answers)
shortest way to create a comma separated object list [duplicate]
(2 answers)
Closed 2 years ago.
I have data that looks like this.
[
{
key: 'myKey'
value: 'myValue'
},
{
key: 'mySecondKey'
value: 'mySecondValue'
},
{
key: 'myThirdKey'
value: 'myThirdValue'
},
]
The amount of objects varies depending on how much values an account has set. I'm trying to return this in a format that looks like this
{
mykey: 'myValue'
mySecondKey: 'mySecondValue'
myThirdkey: 'myThirdValue'
}
Any advice on how I would go about doing this?
You can do something, like
const src = [{key:'myKey',value:'myValue'},{key:'mySecondKey',value:'mySecondValue'},{key:'myThirdKey',value:'myThirdValue'},],
result = Object.assign({}, ...src.map(o => ({[o.key]: o.value})))
console.log(result)
.as-console-wrapper{min-height:100%;}
You can use reduce for this:
const data = [{key:"myKey",value:"myValue"},{key:"mySecondKey",value:"mySecondValue"},{key:"myThirdKey",value:"myThirdValue"}];
const res = data.reduce((obj, {key, value}) => ({...obj, [key]: value}), {});
console.log(res);
Other answers work but I feel like they are a bit complicated, here's a simple for of loop:
const data = [
{
key: 'myKey',
value: 'myValue'
},
{
key: 'mySecondKey',
value: 'mySecondValue'
},
{
key: 'myThirdKey',
value: 'myThirdValue'
}
];
const result = {};
for(const {key, value} of data) {
result[key] = value;
}
console.log(result);
This question already has answers here:
Add a property to a JavaScript object using a variable as the name? [duplicate]
(14 answers)
Closed 3 years ago.
I have object like picture below.
I want to use map() to retrieve the object like
{
"2643216":{pg:1,pt:1},
"1304681":{pg:1,pt:1}
}
Here is my code.
Object.keys(obj).map(function(x){
return {obj[x].number:{'pg':obj[x].pg,'pt':obj[x].pt}}
})
But errors may appear at the obj[x].number.
The debug errors notifies me the ignorance of the : (colon).
Is there mistake I make and any adjustment you can suggest-
or other way can retrieve the object I want?
Thank you.
this should do the job:
function groupByNumber(data) {
return Object
.keys(data)
.reduce(function(result, key) {
var value = data[key];
result[value.number] = { pt: value.pt, pg: value.pg };
return result;
}, {});
};
var data = {
'LKB_something': { number: 1, pg: 1, pt: 5 },
'LKB_something_else': { number: 2, pg: 1, pt: 5 },
'LKB_something_else_1': { number: 3, pg: 1, pt: 5 },
};
console.log('result', groupByNumber(data));
// ES-NEXT would let you be more coincise
const groupByNumber = data => Object.values(data).reduce(
(result, { number, ...rest }) => ({ ...result, [number]: rest }),
{},
);
For a dynamic key in a JavaScript object, you need square brackets to make a computed property name:
return { [obj[x].number]: { "pg": obj[x].pg, "pt": obj[x].pt }}
And your code could be simplified using Object.values and the implicit return of an arrow function, along with destructuring and shorthand property notation, like so:
Object.values(obj).map(({ number, pg, pt }) => ({ [number]: { pg, pt }}))
Note that the above returns an array of objects - if you want an object:
Object.values(obj).reduce((a, { number, pg, pt }) => ({ ...a, [number]: { pg, pt }}), {})
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);