Change property value of all elements in array but need only one - javascript

I create users2 array that has 2 elements. I want to change property value of only one element. The output should be 2 2 2 5, but it is 2 2 5 5, so I change property value of all elements in array.
var users2 = [];
var fieldArray = [];
users2.push({"id": 0}, {"id": 1});
fieldArray.push([{text: "2"}, {text: "2"}, {text: "2"}]);
users2[0].arrShow = fieldArray;
users2[1].arrShow = fieldArray;
console.log(users2[0].arrShow[0][0].text);
console.log(users2[1].arrShow[0][0].text);
users2[1].arrShow[0][0].text = "5";
console.log(users2[0].arrShow[0][0].text);
console.log(users2[1].arrShow[0][0].text);

Your two user objects are both using the same arrShow (which is also accessed via fieldArray), and thus using the same 0th entry of the 0th entry in that array. Naturally, changing the state of that object is reflected regardless of which path you take to look at that object.
Instead, give your users separate arrShows with separate objects in them:
var users2 = [
{
id: 0,
arrShow: [
[{text: "2"}, {text: "2"}, {text: "2"}]
]
},
{
id: 1,
arrShow: [
[{text: "2"}, {text: "2"}, {text: "2"}]
]
}
];
console.log(users2[0].arrShow[0][0].text);
console.log(users2[1].arrShow[0][0].text);
users2[1].arrShow[0][0].text = "5";
console.log(users2[0].arrShow[0][0].text);
console.log(users2[1].arrShow[0][0].text);
Or doing it separately after initialization:
var users2 = [
{id: 0, arrShow: []},
{id: 1, arrShow: []}
];
users2[0].arrShow.push(
[{text: "2"}, {text: "2"}, {text: "2"}]
);
users2[1].arrShow.push(
[{text: "2"}, {text: "2"}, {text: "2"}]
);
console.log(users2[0].arrShow[0][0].text);
console.log(users2[1].arrShow[0][0].text);
users2[1].arrShow[0][0].text = "5";
console.log(users2[0].arrShow[0][0].text);
console.log(users2[1].arrShow[0][0].text);
Or if you need to base arrShow on a separate fieldArray, you need to copy both fieldArray and the objects in it; you can do that with Array#map and Object.assign (which is newish, but readily polyfilled for older environments):
var users2 = [
{id: 0, arrShow: []},
{id: 1, arrShow: []}
];
var fieldArray = [{text: "2"}, {text: "2"}, {text: "2"}];
users2.forEach(function(user) {
user.arrShow.push(
fieldArray.map(function(entry) {
return Object.assign({}, entry);
})
);
});
console.log(users2[0].arrShow[0][0].text);
console.log(users2[1].arrShow[0][0].text);
users2[1].arrShow[0][0].text = "5";
console.log(users2[0].arrShow[0][0].text);
console.log(users2[1].arrShow[0][0].text);

You're probably wanting to avoid repetitive code, and have assumed that assignment will implicitly create a deep copy for you. That's not what happens.
To create a standard object structure, create a function that returns a whole new set of objects.
function makeUser(id) {
return {
id: id,
arrShow: [
[{text: "2"}, {text: "2"}, {text: "2"}]
]
};
}
Then invoke it when you need a new set of data.
var users2 = [
makeUser(0),
makeUser(1),
];
Now mutating one user's data will no longer affect the other.
Here's a demo:
var users2 = [
makeUser(0),
makeUser(1),
];
console.log(users2[0].arrShow[0][0].text);
console.log(users2[1].arrShow[0][0].text);
users2[1].arrShow[0][0].text = "5";
console.log(users2[0].arrShow[0][0].text);
console.log(users2[1].arrShow[0][0].text);
function makeUser(id) {
return {
id: id,
arrShow: [
[{text: "2"}, {text: "2"}, {text: "2"}]
]
};
}
This can also be done with constructor functions or the ES6 class syntax.
class User {
constructor(id) {
this.id = id;
this.arrShow = [
[{text: "2"}, {text: "2"}, {text: "2"}]
];
}
}
var users2 = [
new User(0),
new User(1),
];
console.log(users2[0].arrShow[0][0].text);
console.log(users2[1].arrShow[0][0].text);
users2[1].arrShow[0][0].text = "5";
console.log(users2[0].arrShow[0][0].text);
console.log(users2[1].arrShow[0][0].text);

Related

create and push key value object in array

I have an array :
const data = [{"label": "a", "value": 4}, {"label": "b", "value": 1}, {"label": "c", "value": 2}]
I want to create a new array of objects where I have to give key and value in it.
For eg,:
const newArr = [{1,4},{2,1},{3,2}]
here first item of an object is the key, which has to increase as the number of objects increase, and second item is the value from data.
const data = [{"label": "a", "value": 4}, {"label": "b", "value": 1}, {"label": "c", "value": 2}];
const out = data.map((item, index) => [index + 1, item.value]);
console.log(out);
I hope this is your solution:
const data = [
{
label: 'a',
value: '4'
},
{
label: 'b',
value: '1'
},
{
label: 'c',
value: '2'
},
]
const newArrOfObj = data.reduce((arr, current, index)=> [...arr, {[index+1]:current.value}], []);
console.log(newArrOfObj) //[ { 1: '4' }, { 2: '1' }, { 3: '2' } ]
To push an object into an array, call the push() method, passing it the object as a parameter. For example, arr.push({name: 'Tom'}) pushes the object into the array. The push method adds one or more elements to the end of the array.
index.js
let arr = [];
const obj = {name: 'Tom'};
arr.push(obj);
console.log(arr); // 👉️ [{name: 'Tom'}]

Flatten array of items into the middle of another array

I have an array like so
let items = [
{name: "1"},
{name: "2"},
{name: "3"},
{unwrap: true,
items: [
{name: "4"},
{name: "5"},
{name: "6"},
]
},
{name: "7"},
]
How can I flatten the unwrap object to get the following output?
items = [
{name: "1"},
{name: "2"},
{name: "3"},
{name: "4"},
{name: "5"},
{name: "6"},
{name: "7"},
]
I thought I could do something like this:
items.map(item => {
if(item.hasOwnProperty("unwrap")){
return ... item.items
}
return item
})
However the ...s don't work as a return value.
I have come up with the somewhat clunky using a second array like so:
let output = []
items.forEach((item) => {
if (!item) {
return;
}
if (item.hasOwnProperty("unwrap")) {
return output.push(...item.contents);
}
return output.push(item);
});
flatMap is what you need.
const items=[{name:"1"},{name:"2"},{name:"3"},{unwrap:!0,items:[{name:"4"},{name:"5"},{name:"6"}]},{name:"7"}];
const result = items.flatMap(item => {
if (item.hasOwnProperty('unwrap')) {
return item.items;
}
return item;
});
console.log(result);
You can rely on flatMap:
items.flatMap((x) => {
if (!x.unwrap) {
return x;
}
return x.items;
});
Another way using reduce()
let items = [{name: "1"}, {name: "2"}, {name: "3"}, {unwrap: true, items: [{name: "4"}, {name: "5"}, {name: "6"}, ] }, {name: "7"}, ];
const res = items.reduce((p, c) => p.concat(c.items || c), []);
console.log(res);
Since obj.items won't exist on the regular objects, we can use the || operator to get the desired items, then concat those to the final array.
another way is:
items.flatMap(item=> item?.unwrap ? item.items: item )
or
const result = items.flatMap(item=> item?.unwrap ? item.items: item )

How to merge Javascript Object in array using reduce or array method [duplicate]

I have an array of objects that looks like this:
var countries = [
{id: SWE, value: 5},
{id: DE, value:10},
{id: SWE, anotherValue: 11},
{id: DE, anotherValue: 15}
]
I want to merge array elements by id. The result should look like this:
countries = [
{id: SWE, value: 5, anotherValue: 11},
{id: DE, value:10, anotherValue:15}
]
Right now, I'm doing this with a for loop and a lot of if and else.
Question: is there any (more elegant) javascript inbuilt functionality to achieve this?
I've tried googling this, the problem is that I'm not sure what to Google for (I'm a javascript newby). Any help is appreciated.
try this:
function mergeById(a){
var obj={};
a.forEach(function(e){
if(e && e.id){
obj[e.id] = obj[e.id] || {};
for(var _k in e) obj[e.id][_k] = e[_k]
}
});
return Object.keys(obj).map(function (key) {return obj[key]});
}
var countries = [
{id: 'SWE', value: 5},
{id: 'DE', value:10},
{id: 'SWE', anotherValue: 11},
{id: 'DE', anotherValue: 15}
]
document.write(JSON.stringify(mergeById(countries)))

JS - Insert an object inside an object having a same data

I'm arranging series of data having a same data in it
var arr = [{id: 1, parent: "a"}, {id: 2, parent: "b"}];
var cArr = [
{parentID: 1, a1: "1"},
{parentID: 1, a1: "2"},
{parentID: 2, a1: "3"},
{parentID: 2, a1: "4"}
];
and I want to join them and will look like this
var array = [
{ id: 1, parent: "1", data: [{ a1: "1"}, { a1: "2"}] },
{ id: 2, parent: "2", data: [{ a1: "3"}, { a1: "4"}] }
];
How do I add variable like parent and data inside of object array?
How do I access id: 1, parent: "1", data: [{ a1: "1"}, { a1: "2"}]? Is it like array[0]?
I'm new to JS and like this if I have errors I'm so sorry. I'm using console.log() to check things up
You can achieve it like this:
var array = [{ parent: "1", data: [{ a1: "1"}, { a1: "2"}] },
{parent: "2", data: [{ a1: "3"}, { a1: "4"}]
}];
console.log(array[0].parent); // 1
console.log(array[0].data) // [{ a1: "1"}, { a1: "2"}]
To add an item just do like this using .push method
array.push({ parent: "3", data: [{ a1: "5"}, { a1: "6"}] });
Iterate the arr with Array.map(), and create a new object with the content of the original object using object spread. To get the respective items from cArr use Array.slice() with the index of the current item:
const arr = [{parent: "1"}, {parent: "2"}];
const cArr = [{a1: "1"}, {a1: "2"}, {a1: "3"}, {a1: "4"}];
const result = arr.map((o, i) => ({
...o, // copy the original object's content
data: cArr.slice(i * 2, i * 2 + 2) // slice the sub-array from cArr
}));
console.log(result);

Grouping elements in javascript

I've created this list by grouping elements from another list (with d3.nest)
array = [ {key: "6S", values: [{Id: "1234a", ECTS: 3},
{Id: "1234b", ECTS: 3}]},
{key: "7S", values: [{Id: "1534a", ECTS: 5},
{Id: "154b", ECTS: 4},]} ]
From this list I want to create something like this:
array = [{key: "6S", values: { 3: [{Id: "1234a"}, {Id: "1234b"}]}},
{key: "7S", values: { 5: [{Id: "1534a"}], 4: [{Id:"1534a"}]}}]
Actually I want to group the data for each key (6S, 7S) by ECTS.
I've tried with _.groupBy.... but is not working. The problem is that the elements that I want to group are objects, already grouped once.
Any idea about how I could group the items?
You can try following
var array = [ {key: "6S", values: [{Id: "1234a", ECTS: 3}, {Id: "1234b", ECTS: 3}]}, {key: "7S", values: [{Id: "1534a", ECTS: 5}, {Id: "154b", ECTS: 4},]} ];
array.forEach((obj) => {
var values = {};
// Iterate over array and create the updated value
obj.values.forEach((item) => {
values[item.ECTS] = values[item.ECTS] || [];
values[item.ECTS].push({"Id" : item.Id});
});
// Set the updated value in object
obj.values = values;
});
console.log(array);
var array = [{
key: "6S",
values: [{
Id: "1234a",
ECTS: 3
},
{
Id: "1234b",
ECTS: 3
}
]
},
{
key: "7S",
values: [{
Id: "1534a",
ECTS: 5
},
{
Id: "154b",
ECTS: 4
},
]
}
]
array = array.map(function(v1) {
var updatedVal = v1.values.reduce(function(obj, v2) {
obj[v2.ECTS] = obj[v2.ECTS] || [];
obj[v2.ECTS].push({
Id: v2.Id
});
return obj;
}, {});
v1.values = updatedVal;
return v1;
});
console.log(array);

Categories