Dynamically assign property to object [closed] - javascript

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I have two arrays
var arr1 = [
{id: 1, name:'Rick'},
{id: 2, name:'Daryl'},
{id: 3, name:'Carl'},
{id: 4, name:'Negan'}
];
var arr2 = ['Colt', 'Crossbow', 'Glock', 'Bat'];
I want to assign items from arr2 to the arr1 so the final result would be something like this
arr1 = [
{id: 1, name: 'Rick', weapon: 'Colt'},
{id: 2, name: 'Daryl', weapon: 'Crossbow'},
{id: 3, name: 'Carl', weapon: 'Glock'},
{id: 4, name: 'Negan', weapon: 'Bat'}
];
What is the best approach to achieve this? Any suggestion/example will be appreciated!

You can use Array.prototype.forEach with a value and an index to modify arr1:
arr2.forEach((v, i) => arr1[i].weapon = v);

Or if you don't like forEach you can use map and spread
var arr1 = [
{id: 1, name:'Rick'},
{id: 2, name:'Daryl'},
{id: 3, name:'Carl'},
{id: 4, name:'Negan'}
];
var arr2 = ['Colt', 'Crossbow', 'Glock', 'Bat'];
result = arr1.map((pr, index) => ({...pr, weapon: arr2[index]}))
console.log(result);

var arr1 = [
{id: 1, name:'Rick'},
{id: 2, name:'Daryl'},
{id: 3, name:'Carl'},
{id: 4, name:'Negan'}
];
var arr2 = ['Colt', 'Crossbow', 'Glock', 'Bat'];
arr2.forEach((value, index) => {
arr1[index].weapon = value
// OR
arr1[index]['weapon'] = value
// OR
Object.defineProperty(arr1[index], "weapon", {
value: value,
writable : true,
enumerable : true,
configurable : true });
})

Related

compare 2 arrays and get key of one with value of the other one in React [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 10 months ago.
The community is reviewing whether to reopen this question as of 8 months ago.
Improve this question
So in React, I have 2 arrays:
const arr1 = [
{id: 1, name: 'Hello'}
{id: 2, name: 'Dear'}
{id: 3, name: 'World'}
]
const arr2 = ['Hello', 'Dear']
I would like the arr2 values to be the id of the arr1 and end up with this:
const arr2 = [1, 2]
Thank you very much
Loop through arr2 and find the item with the same name in arr1. Then take the id of that item.
const arr1 = [
{id: 1, name: 'Hello'},
{id: 2, name: 'Dear'},
{id: 3, name: 'World'}
]
let arr2 = ['Hello', 'Dear']
let nameToId = arr1.reduce((result, item) => ({ ...result, [item.name]: item.id}), {});
arr2 = arr2.map((name) => nameToId[name]);
console.log(arr2);

how to find the indexes of a given key in array of objects [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
What I need is to find the indexes of a given key in array of objects. for example, to combine the the values of objects with identical keys into one object with one key and the sum of its values, as shown below:
cart = [{id: 123, quantity: 3}, {id: 456, quantity: 2}, {id: 123, quantity: 2}, {id: 456, quantity: 4}]
A quick and bit ugly solution is:
cart = [{id: 123, quantity: 3}, {id: 456, quantity: 2}, {id: 123, quantity: 2}, {id: 456, quantity: 4}];
newCart = [];
for (var i = 0; i < cart.length; i++) {
found = false;
for (var j = 0; j < newCart.length; j++) {
if (cart[i].id == newCart[j].id) {
newCart[j].quantity += cart[i].quantity;
found = true;
}
}
if (!found) {
newCart.push(cart[i]);
}
}
Try:
const cart = [{id: 123, quantity: 3}, {id: 456, quantity: 2}, {id: 123, quantity: 2}, {id: 456, quantity: 4}]
const sumOfId = (id) => cart.filter(c => c.id === id).reduce((a, b) => a + b.quantity, 0);
const cartProducts = cart.filter((v,i,a)=>a.findIndex(t=>(t.id === v.id))===i);
const newCart = [];
for(let i = 0; i < cartProducts.length; i++) {
const id = cartProducts[i].id;
newCart.push(id, sumOfId(id));
}

JavaScript: How to group two-dimensional array based matching fields on two input arrays? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I have the following arrays a and b as shown:
var a = [
{id: 1, name: "phone"},
{id: 2, name: "nick"}
];
var b = [
{id: 7, parentId: 1, name: "phone_item1"},
{id: 8, parentId: 2, name: "phone_item2"},
{id: 9, parentId: 1, name: "nick_item1"},
{id: 10, parentId: 2, name: "nick_item2"}
];
//You want to filter by A array id
const filterIds = a.map(({ id }) => id);
//My attempt
const c = Object.values(b.reduce((r, c) => {
r[c.parentId] = r[c.parentId] || [];
r[c.parentId].push(c);
return r;
}, {}));
console.log(c)
I am trying to obtain the following two-dimensional array:
[[
{id: 7, parentId: 1, name: "phone_item1"},
{id: 9, parentId: 1, name: "nick_item1"}
],[
{id: 8, parentId: 2, name: "phone_item2"},
{id: 10, parentId: 2, name: "nick_item2"}
]]
The resulting array should be according to the comparison between the id of array a and parentId of array b, so that this style of 2D array results. For some reason my attempt is not working - can you help me?
Not suring if I'm missing something here - assuming I understand your question correctly, a simple implementation would be to map each item of a such that the mapping returns a filtered subset of b on matches between bItem.parentId === aItem.id (where aItem and bItem are items of respective lists being iterated):
var a = [
{id: 1, name: "phone"},
{id: 2, name: "nick"}
];
var b = [
{id: 7, parentId: 1, name: "phone_item1"},
{id: 8, parentId: 2, name: "phone_item2"},
{id: 9, parentId: 1, name: "nick_item1"},
{id: 10, parentId: 2, name: "nick_item2"}
];
/* Map each item in a to a classification of b against a */
const result = a.map(aItem => {
/* For current aItem, return a subset of b, filtered by matches
on bItem.parentId === aItem.id (ie the classification criteria) */
return b.filter(bItem => bItem.parentId === aItem.id)
});
console.log(result)
Type error c.paentId and relation for filterIds which was missing:
var a = [
{id: 1, name: "phone"},
{id: 2, name: "nick"}
];
var b = [
{id: 7, parentId: 1, name: "phone_item1"},
{id: 8, parentId: 2, name: "phone_item2"},
{id: 9, parentId: 1, name: "nick_item1"},
{id: 10, parentId: 2, name: "nick_item2"}
];
const filterIds = a.map(({ id }) => id);
//The problem code
const c = Object.values(b.reduce((r, c) => {
r[c.parentId] = filterIds.includes(c.parentId) && r[c.parentId] || [];
r[c.parentId].push(c);
return r;
}, {}));
console.log(c);

How can I merge two or more arrays containing several objects into one and increment their IDs?

I have three arrays of objects like so
const arr1 = [{id: 1, name: 'Jay'}, {id: 2, name: 'Kay'}];
const arr2 = [{id: 1, name: 'Pete'}, {id: 2, name: 'Liam'}];
const arr3 = [{id: 1, name: 'Baby'}, {id: 2, name: 'Neeson'}, {id: 3, name: 'Kobe'}];
and I want to merge them into a single array like this
const bigArray = [{id: 1, name: 'Jay'}, {id: 2, name: 'Kay'},{id: 3, name: 'Pete'}, {id: 4, name: 'Liam'}, {id: 5, name: 'Baby'}, {id: 6, name: 'Neeson'}, {id: 7, name: 'Kobe'}];
I know I can spread them into a single array using the spread operator but I also need the IDs incremented when they are joined. How can I achieve that?
Reassign the id based on the index:
const merged = [...arr1, ...arr2, ...arr3];
merged.forEach((el, index) => el.id = index + 1);
Add all the array in a single array and than map over it and change index according to need.
const arr1 = [{id: 1, name: 'Jay'}, {id: 2, name: 'Kay'}];
const arr2 = [{id: 1, name: 'Pete'}, {id: 2, name: 'Liam'}];
const arr3 = [{id: 1, name: 'Baby'}, {id: 2, name: 'Neeson'}, {id: 3, name: 'Kobe'}];
let arr = [...arr1,...arr2,...arr3]
let op = arr.map((ele, index) => ({...ele, id: index+1}) )
console.log(op)
You can combine the arrays to a single array using rest parameters and Array.flat(), and then you can use Array.map() to update the objects with the id generated from the index:
const flatAndInc = (...args) =>
args.flat()
.map((o, idx) => ({
...o,
id: idx + 1
}));
const arr1 = [{id: 1, name: 'Jay'}, {id: 2, name: 'Kay'}];
const arr2 = [{id: 1, name: 'Pete'}, {id: 2, name: 'Liam'}];
const arr3 = [{id: 1, name: 'Baby'}, {id: 2, name: 'Neeson'}, {id: 3, name: 'Kobe'}];
const result = flatAndInc(arr1, arr2, arr3);
console.log(result);
You could map new objects without mutating the given data.
const
arr1 = [{id: 1, name: 'Jay'}, {id: 2, name: 'Kay'}],
arr2 = [{id: 1, name: 'Pete'}, {id: 2, name: 'Liam'}],
arr3 = [{id: 1, name: 'Baby'}, {id: 2, name: 'Neeson'}, {id: 3, name: 'Kobe'}],
result = [arr1, arr2, arr3].reduce(
(id => (r, a) => (a.forEach(({ name }) => r.push({ id: id++, name })), r))(1),
[]
);
console.log(result);
All of the other answers are valid, and are mostly more efficient and easier than mine. However, my answer is one of the easiest to understand.
My code uses Spread Syntax (...) to create the big array, but all that does is combines the arrays. Then, I use a .forEach() loop to loop through the array, and redefine the id. Then I incremented the id variable, so that the id's were in order.
const arr1 = [{id: 1, name: 'Jay'}, {id: 2, name: 'Kay'}];
const arr2 = [{id: 1, name: 'Pete'}, {id: 2, name: 'Liam'}];
const arr3 = [{id: 1, name: 'Baby'}, {id: 2, name: 'Neeson'}, {id: 3, name: 'Kobe'}];
let id = 1;
const bigArray = [...arr1, ...arr2, ...arr3];
bigArray.forEach(e => {
e.id = id;
id++;
});
console.log(bigArray);
You can use Array.from and spread
const arr1 = [{id: 1, name: 'Jay'}, {id: 2, name: 'Kay'}];
const arr2 = [{id: 1, name: 'Pete'}, {id: 2, name: 'Liam'}];
const arr3 = [{id: 1, name: 'Baby'}, {id: 2, name: 'Neeson'}, {id: 3, name: 'Kobe'}];
var result = Array.from([...arr1, ...arr2, ...arr3], ({name}, i)=>{ return {id: i + 1, name} });
console.log(result);
You can use reduce() map() and Spread Syntax.
Pass an array of all the arrays you want to merge to function
Flat that array using spread operator.
Then use reduce() to convert all the arrays to single dimensional array.
At last use map() and set it id property to index + 1
const arr1 = [{id: 1, name: 'Jay'}, {id: 2, name: 'Kay'}];
const arr2 = [{id: 1, name: 'Pete'}, {id: 2, name: 'Liam'}];
const arr3 = [{id: 1, name: 'Baby'}, {id: 2, name: 'Neeson'}, {id: 3, name: 'Kobe'}];
function merge(arrays){
return [...arrays].reduce((ac,a) => [...ac,...a],[]).map((x,i) => ({...x,id:i+1}));
}
console.log(merge([arr1,arr2,arr3]));

Compare the elements of two arrays by Id and remove the elements from the one array that are not presented in the other

I have two arrays of objects like this:
var arr1 = [{Id: 1, Name: "Test1"}, {Id: 2, Name: "Test2"}, {Id: 3, Name: "Test3"}, {Id: 4, Name: "Test4"}]
var arr2 = [{Id: 1, Name: "Test1"}, {Id: 3, Name: "Test3"}]
I need to compare the elements of the two arrays by Id and remove the elements from arr1 that are not presented in arr2 ( does not have element with that Id). How can I do this ?
var res = arr1.filter(function(o) {
return arr2.some(function(o2) {
return o.Id === o2.Id;
})
});
shim, shim, shim.
You can use a function that accepts any number of arrays, and returns only the items that are present in all of them.
function compare() {
let arr = [...arguments];
return arr.shift().filter( y =>
arr.every( x => x.some( j => j.Id === y.Id) )
)
}
var arr1 = [{Id: 1, Name: "Test1"}, {Id: 2, Name: "Test2"}, {Id: 3, Name: "Test3"}, {Id: 4, Name: "Test4"}];
var arr2 = [{Id: 1, Name: "Test1"}, {Id: 3, Name: "Test3"}, {Id: 30, Name: "Test3"}];
var arr3 = [{Id: 1, Name: "Test1"}, {Id: 6, Name: "Test3"}, {Id: 30, Name: "Test3"}];
var new_arr = compare(arr1, arr2, arr3);
console.log(new_arr);
function compare() {
let arr = [...arguments]
return arr.shift().filter( y =>
arr.every( x => x.some( j => j.Id === y.Id) )
)
}
Making use of a hash (a Set) will give a performance gain:
var arr1 = [{Id: 1, Name: "Test1"}, {Id: 2, Name: "Test2"},
{Id: 3, Name: "Test3"}, {Id: 4, Name: "Test4"}];
var arr2 = [{Id: 1, Name: "Test1"}, {Id: 3, Name: "Test3"}];
arr1 = arr1.filter(function (el) {
return this.has(el.Id);
}, new Set(arr2.map(el => el.Id)));
console.log(arr1);
A new Set is created that gets the Id values from arr2:
"1","3"
That Set is passed as the thisArg to filter, so that within the filter callback it is available as this.

Categories

Resources