I have two array of objects:
`let arr1 = [
{"var1":1, "id": 1},
{"var2":2, "id": 2},
{"var3":3, "id": 3}]
`let arr2 = [
{"someVal":1, "data":123, "id": 1},
{"someVal":2, data":456, "id": 2}]
I need to add in to objects in 'arr1' parameters someVal from objects in arr2 by id's.
Result should be
`let arr1 = [
{"var1":1, "id": 1, "someVal":1},
{"var2":2, "id": 2, "someVal":1},
{"var3":3, "id": 3}]
Would that work for you?
const arr1 = [{"var1":1,"id":1},{"var2":2,"id":2},{"var3":3,"id":3}],
arr2 = [{"someVal":1,"id":1},{"someVal":2,"id":2}]
result = arr1.map(o => {
const someVal = arr2.find(({id}) => o.id == id)?.someVal
return {...o, ...(someVal ? {someVal} : {})}
})
console.log(result)
.as-console-wrapper{min-height:100%;}
You could use two forEach loops to add the corresponding values to arr1.
let arr1 = [
{"var1":1, "id": 1},
{"var2":2, "id": 2},
{"var3":3, "id": 3}]
let arr2 = [
{"someVal":1, "id": 1},
{"someVal":2, "id": 2}]
arr1.forEach(elem_arr1 => {
arr2.forEach(elem_arr2 => {
if(elem_arr1.id == elem_arr2.id){
elem_arr1["someVal"]= elem_arr2.someVal
}
})
})
console.log(arr1)
arr1.forEach((element) => {
arr2.map(item => {
if(element.id == item.id)
element.someVal = item.someVal;
})
});
you can use forach and object.assign to achieve this
let arr1 = [{"var1":1, "id": 1},{"var2":2, "id": 2},{"var3":3, "id": 3}]
let arr2 = [{"someVal":1, "data":123, "id": 1},{"someVal":2, "data":456, "id": 2}]
arr1.forEach(o=>{arr2.forEach(y=>{ if(o.id==y.id) Object.assign(o,y)})})
console.log(arr1)
Related
I have two array of objects,arr1 and arr2
if taskId and id same then retreive from arr1
How to check based on property from arr1 and arr2 in javascript
var arr1= [
{"name":"refresh task","memberIds":[981],"dueOn":"2022-08-30","taskId":19},
{"name":"ref one","memberIds":[981,982],"dueOn":"2022-08-25","taskId":null}
]
var arr2 =[
{
"country": "IN",
"tasks": [
{id: 19, "name": "abc" },
{id: 20, "name": "xyz" }
]
}
]
I tried
var result = arr1.filter(e=>e.taskId===(arr2.map(i=>i.tasks.map(t=>t.id))
Expected Output
[
{"name":"refresh task","memberIds":[981],"dueOn":"2022-08-30","taskId":19}
]
Using Set, Array#flatMap, and [Array#map][3], get the list of task ids in arr2``
Using Array#filter, and Set#has, return the resulting array where taskId is in the above set
const
arr1= [
{"name":"refresh task", "memberIds":[981], "dueOn":"2022-08-30", "taskId":19},
{"name":"ref one", "memberIds":[981,982], "dueOn":"2022-08-25", "taskId":null}
],
arr2 =[
{
"country": "IN",
"tasks": [ {"id": 19, "name": "abc"}, {"id": 20, "name": "xyz"} ]
}
];
const taskIdSet = new Set(
arr2.flatMap(({ tasks = [] }) => tasks.map(({ id }) => id))
);
const result = arr1.filter(({ taskId }) => taskIdSet.has(taskId));
console.log(result);
EDIT:
To get "I have two arrays of objects, arr1, and arr2 if taskId and id not same then retrieve from arr2":
const
arr1= [
{"name":"refresh task", "memberIds":[981], "dueOn":"2022-08-30", "taskId":19},
{"name":"ref one", "memberIds":[981,982], "dueOn":"2022-08-25", "taskId":null}
],
arr2 =[
{
"country": "IN",
"tasks": [ {"id": 19, "name": "abc"}, {"id": 20, "name": "xyz"} ]
}
];
const taskIdSet = arr1.reduce((taskIdSet, { taskId }) => {
if(taskId !== null) { taskIdSet.add(taskId); }
return taskIdSet;
}, new Set);
const result = arr2
.flatMap(({ tasks = [] }) => tasks)
.filter(({ id }) => !taskIdSet.has(id));
console.log(result);
This works too:
var result = arr1.filter(e=>{
for(let obj of arr2){
for(let task of obj.tasks){
return e.taskId === task.id;
}
}
})
I have this array which holds objects;
let arr = [
{
"id": 1,
"level": "2",
},
{
"id": 2,
"level": "3",
}
]
By default the array has keys starting from 0 and it looks like this:
[
0: {id: 1, level:2},
1: {id: 2, level:3}
]
How can I transform it so that the keys are the values of the property 'level'?
It should look like this:
[
2: {id:1, level:2},
3: {id:1, level:3}
]
So far I have tried this but it doesn't remove the original keys:
arr.map((v, k) => ({[v.level]: v}));
So I have something like this:
[
0: {2:
{id: 1, level:2}
},
1: {3:
{id: 2, level:3}
}
]
You need to populate a new array using reduce:
arr.reduce((prev, curr) => { prev[curr.level] = curr; return prev }, [])
I think I prefer the reduce method, but you could also construct an "array-like" (i.e. an object with numeric keys and a length property) and pass it to Array.from
const maxIdx = Math.max(...arr.map(v => parseInt(v.level, 10)))
const arrLen = maxIdx + 1;
const arrayLike = {
...Object.fromEntries(arr.map(v => [v.level, v])),
length: arrLen
};
const mappedArray = Array.from(arrayLike);
For output of
[undefined, undefined, {
"id": 1,
"level": "2"
}, {
"id": 2,
"level": "3"
}]
array1 = [{
"id": 1,
"name": "aaa",
},
{
"id": 2,
"name": "bbb"
},
{
"id": 5,
"name": "ccc"
},
{
"id": 6,
"name": "ddd"
},
{
"id": 8,
"name": "eee"
},
{
"id": 12,
"name": "fff"
}]
array2 = [ 5, 6, 8 ,12]
Resulting Array = [ {name: "ccc"}, {name: "ddd"} , {name: "eee"}, {name: "fff"} ]
I am looking to map both arrays to get matching id numbers and get copy the names in the resulting arrray but I didn't succeed. Can you please suggest me how to do it?
Thank you
You could try the following. Basically, you're filtering the first array based on whether or not the id exists in the 2nd array and then mapping it back by only selecting the key(s) you want.
var resultArray = array1.filter(function(arr) {
return array2.indexOf(arr.id) !== -1;
}).map(function(item) {
return {
name: item.name
};
});
Let's turn array1 into an object first, that maps ids to the corresponding objects:
var idMap = {}
array1.forEach(function(element) {
idMap[element.id] = element
})
You can then get the result you want by doing
var result = array2.map(function(id) {
return idMap[id]
});
Try This:
array1 = [{"id": 1,"name": "aaa"},{"id": 2,"name": "bbb"},{"id": 5,"name": "ccc"},{"id": 6,"name": "ddd"},{"id": 8,"name": "eee"},{"id": 12,"name": "fff"}] ;
array2 = [ 5, 6, 8 ,12];
var result = array1.filter(item => array2.includes(item.id)).map(({id,name}) => ({name}));
console.log( result );
I'm trying to achieve something like this:
let obj = [
{"id": "1"},
{"id": "2"},
{"id": "3"}
]
const arr = ["a", "b", "c"];
obj = addAtoO(arr, obj); // expected outcome: obj = [{"id": "1", "text": "a"}, {"id": "2", "text": "b"}, {}]
In words: dynamically add values from an array to an object as new values.
Here's what I'm trying:
const addAtoO = (a, o) => {
o.map((i) => {
console.log(Object.keys(i));
// a.forEach((e) => {
// console.log(e);
// });
i['text'] = 'something'; // just add text for testing
});
return o;
};
obj = addAtoO(arr, obj);
console.log('result:');
console.log(obj);
But it seems like there must be a better way.
Thank you so much guys. All your solutions are correct. I had to mark one so I picked the one that is the closest to this specific question.
You can use map as you are using , & use it's index to get the value from arr array and create a new object with values from obj & arr
let obj = [{
"id": "1"
},
{
"id": "2"
},
{
"id": "3"
}
]
const arr = ["a", "b", "c"];
let output = obj.map(function(item, index) {
return Object.assign({}, item, {
text: arr[index]
})
})
console.log(output)
Else you can also use forEach and mutate the original obj array
let obj = [{
"id": "1"
},
{
"id": "2"
},
{
"id": "3"
}
]
const arr = ["a", "b", "c"];
obj.forEach(function(item, index) {
item.text = arr[index]
})
console.log(obj)
The way you are using addAtoO suggests that you don't care about altering the original objects. If that's the case, then a simple forEach will do:
const addAtoO = (arr, obj) => arr.forEach((t, i) => obj[i].text = t);
addToO alters the original array of objects obj, so it doesn't return anything.
Example:
const addAtoO = (arr, obj) => arr.forEach((t, i) => obj[i].text = t);
let obj = [ {"id": "1"}, {"id": "2"}, {"id": "3"}];
const arr = ["a", "b", "c"];
addAtoO(arr, obj);
console.log(obj);
You can use .map() like this:
const arr1 = [
{"id": "1"},
{"id": "2"},
{"id": "3"}
]
const arr2 = ["a", "b", "c"];
const merge = (a1, a2) => a1.map((o, i) => Object.assign({}, o, {text: a2[i]}));
console.log(merge(arr1, arr2));
.as-console-wrapper { max-height: 100% !important; top: 0; }
For more flexibility, i suggest to use a key for the function as well as parameter.
const addTo = (objects, values, key) =>
objects.map((o, i) => Object.assign({}, o, { [key]: values[i] }));
console.log(addTo([{ id: "1" }, { id: "2" }, { id: "3" }], ["a", "b", "c"], 'text'));
If you like to mutate the given objects, just remove the empty object from Object.assign.
const addTo = (objects, values, key) =>
objects.map((o, i) => Object.assign(o, { [key]: values[i] }));
var objects = [{ id: "1" }, { id: "2" }, { id: "3" }];
addTo(objects, ["a", "b", "c"], 'text');
console.log(objects);
There is no need to make things complicated. Just use a forEach.
let obj = [{
"id": "1"
},
{
"id": "2"
},
{
"id": "3"
}
]
const arr = ["a", "b", "c"];
obj.forEach((object, index) => {
object.text = arr[index]
})
console.log(obj)
Can anyone help me in merging of two array of objects please using loadash in javascript? Below is the example arrays. I tried with _merge
arr 1= [
{
"areaId": 1,
"areaName": "areanam222",
"businessExecutiveId": 1
},
{
"areaId": 2,
"areaName": "arename",
"businessExecutiveId": 1
}
]
arr2 =[
{
"id": 1,
"name": "BN",
}
]
arrResult =[
{
"areaId": 1,
"areaName": "areanam222",
"businessExecutiveId": 1,
"id": 1,
"name": "BN"
}, {
"areaId": 2,
"areaName": "arename",
"businessExecutiveId": 1,
"id": 1,
"name": "BN"
}
]
I tried with below option but it is returning only one record.
var arrResult = _(list).keyBy('businessExecutiveId').merge(_.keyBy(this.typeaheadDataList, 'id')).values() .value();
I also tried with below
const c = _.assign([], arr1, arr2);
reslut I am getting is like below
{
id: 1,
name: "BN"
},
{
areaId: 1,
areaName: "ASas",
businessExecutiveId: 1,
id: 1,
name: "BN"
}
Please help me
You don't need lodash to do this. Why not just use javascripts reduce function to merge all object keys from arr2 objects into the objects of array 1, like so
arr1.reduce((arr, obj) => {
const newObj = arr2.reduce((o, insideObj) => ({
...o,
...insideObj
}), obj)
return [...arr, newObj]
}, [])
arr1.reduce((arr, obj) => {
const newObj = arr2.reduce((o, insideObj) => ({
...o,
...insideObj
}), obj)
return [...arr, newObj]
}, [])
I resolved it by using below code.
_.map(list, function(item) {
return _.merge(item, _.find(temp, function(o) {return o.id == item.businessExecutiveId }) );
});
If we had array comprehension, we could have used something like this:
[
for (a of arr1)
for (b of arr2)
if(a.businessExecutiveId === b.id) {...a, ...b}
]
Without array comprehension, we use flatMap:
_(arr1).flatMap(a =>
_(arr2).flatMap(b =>
a.businessExecutiveId === b.id ? [{...a, ...b}] : []
).value()
).value()
var arr1= [
{
"areaId": 1,
"areaName": "areanam222",
"businessExecutiveId": 1
},
{
"areaId": 2,
"areaName": "arename",
"businessExecutiveId": 1
},
{
"areaId": 3,
"areaName": "bname",
"businessExecutiveId": 2
}
]
var arr2= [
{
"id": 1,
"name": "BN",
},
{
"id": 2,
"name": "CM",
}
]
res = _(arr1).flatMap(a =>
_(arr2).flatMap(b =>
a.businessExecutiveId === b.id ? [{...a, ...b}] : []
).value()
).value()
console.log(res)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>