Add properties to an array of objects from a separate array - javascript

I need to add properties to an array of objects from a separate array.
I have 2 arrays. The first array is an array of objects. The second array is an array of Ints. I want to add a new property to each object in the array from the array of Ints.
Example:
var arrOfObj = [
{
name: "eve"
},
{
name: "john"
},
{
name: "jane"
}
];
var arr = [0, 1, 2]
//Desired output
var arrOfObj = [
{
name: "eve",
num: 0
},
{
name: "john",
num: 1
},
{
name: "jane",
num: 2
}
];
Thanks for the help!

You could do with Array#forEach
var arrOfObj = [ { name: "eve" }, { name: "john" }, { name: "jane" }];
var arr = [0, 1, 2];
arrOfObj.forEach((a,i)=>{ a.num = arr[i]});
console.log(arrOfObj)

Related

filter array of object using an array [duplicate]

This question already has an answer here:
Filter array of object from another array
(1 answer)
Closed 3 years ago.
I want to filter an array of objects using an array but I want the results on the basis of array index and the result should be repeated when the array index value is repeated.
const data = [{
id='1',
name:'x'
},
{
id='4',
name:'a'
},
{
id='2',
name:'y'
},
{
id='3',
name:'z'
}
]
cons idArray = [1,4,3,2,4,3,2]
I have tried following code and get the result only once
const filteredData = data.filter(arrayofObj => idArray.includes(arrayofObj.id))
console.log(filteredData)
expected output is
expected output is =
[{id = '1,name:'x'},{id='4',name:'a'},{
id='3',
name:'z'
},
{
id='2',
name:'y'
},{
id='4',
name:'a'
},
{
id='3',
name:'z'
},{
id='2',
name:'y'
}]
First convert data array into Object with id's as keys.
Second, use map method over idArray and gather objects from above object.
const data = [
{
id: "1",
name: "x"
},
{
id: "4",
name: "a"
},
{
id: "2",
name: "y"
},
{
id: "3",
name: "z"
}
];
const dataObj = data.reduce((acc, curr) => {
acc[curr.id] = { ...curr };
return acc;
}, {});
const idArray = [1, 4, 3, 2, 4, 3, 2];
const results = idArray.map(id => ({ ...dataObj[id] }));
console.log(results);
You could map with a Map.
const
data = [{ id: '1', name: 'x' }, { id: '4', name: 'a' }, { id: '2', name: 'y' }, { id: '3', name: 'z' }],
idArray = [1, 4, 3, 2, 4, 3, 2],
result = idArray.map(Map.prototype.get, new Map(data.map(o => [+o.id, o])));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Function question, angular typescript, match id values from 2 arrays to get the index from one of them

I have a two arrays, and I want to match their ID values and then get the index of that id in the second array. I know this sounds simple but I'm super new to the syntax, and I'm having a hard time picturing what this should look like. can anyone model that in simple terms?
example functionality:
var array1 = { id:2, name: 'preston'}
array2 = {
{
id: 1
name: 'john'
},
{
id: 2
name: 'bob'
}
Expected behavior
where both ids = 2, give index of array2.
returns 1
can anyone show me?
You can use findIndex on array2
Try this:
var array1 = {
id: 2,
name: 'preston'
}
var array2 = [{
id: 1,
name: 'john'
},
{
id: 2,
name: 'bob'
}
]
console.log(array2.findIndex(item => item.id === array1.id))
Or use indexOf with map if you want support for IE as well without polyfills.
var array1 = {
id: 2,
name: 'preston'
}
var array2 = [{
id: 1,
name: 'john'
},
{
id: 2,
name: 'bob'
}
]
console.log(array2.map(item => item.id).indexOf(array1.id))
Iterate over each item in array1 using forEach(). Find each item's index in array2 using findIndex().
var array1 = [{id:2, name: "preston"}];
var array2 = [{id: 1, name: "john" }, {id: 2, name: "bob" }];
array1.forEach(item => {
let index = array2.findIndex(obj => obj.id === item.id);
console.log(index);
});

Immutable.js algorithm: List.update_or_add(item)

I want to concatenate 2 lists in immutable.js.
Both lists have this structure: { id, value }
The algorithm concatenate should do this:
If an ID exists in both list1 and list2 take the value from list2.
let list1 = [
{ id: 1, value: 'foo' },
{ id: 3, value: 'bar' },
{ id: 2, value: 'baz' },
]
let list2 = [
{ id: 1, value: 'quux' }, // id 1 exists in list1
{ id: 4, value: 'asd' },
]
let result = [
{ id: 1, value: 'quux' }, // from list 2
{ id: 3, value: 'bar' },
{ id: 2, value: 'baz' },
{ id: 4, value: 'asd' },
]
If Immutable.js has this functionality with another type (eg. Dictionary), I could also use that.
Algorithms for union
First you have to maintain two map with key as id and value as object then check for length of array which is of bigger size and pass the bigger size array with small size map to merged function there you can iterate over the array and check if it's exists in the map if yes then update the object and delete that row from map otherwise add the object into output. After the for loop complete check if map has element present then push all the values from map into output array and return;
index.js
const old = [
{ id: 1, value: 'foo' },
{ id: 3, value: 'bar' },
{ id: 2, value: 'baz' },
];
const newa = [
{ id: 1, value: 'quux' }, // update
{ id: 4, value: 'asd' }, // push
];
function merged(input,filterMap){
var output = [];
input.forEach(function(eachRow){
if(filterMap.hasOwnProperty(eachRow.id)){
output.push(Object.assign(eachRow,filterMap[eachRow.id]));
delete filterMap[eachRow.id];
}else{
output.push(eachRow);
}
});
if(Object.keys(filterMap).length > 0){
output = output.concat(Object.values(filterMap));
}
return output;
}
function parseData(first,second){
var mapFirst = {},
mapSecond = {};
var output = [];
first.forEach(function(eachRow){
mapFirst[eachRow.id] = eachRow;
});
second.forEach(function(eachRow){
mapSecond[eachRow.id] = eachRow;
});
if(first.length > second.length){
return merged(first,mapSecond);
}else{
return merged(second,mapFirst);
}
}
console.log(parseData(old,newa));
Working jsFiddle demo - https://jsfiddle.net/qz25hnmf/

Compare two Arrays with Objects and create new array with unmatched objects

I have the following two Javascript arrays:
const array1 = [{ id: 1}, { id: 2 }, { id: 3 }, { id: 4}];
const array2 = [{ id: 1}, { id: 3 }];
I now want a new array array3 that contains only the objects that aren't already in array2, so:
const array3 = [{ id: 2}, { id: 4 }];
I have tried the following but it returns all objects, and when I changed the condition to === it returns the objects of array2.
const array3 = array1.filter(entry1 => {
return array2.some(entry2 => entry1.id !== entry2.id);
});
Any idea? ES6 welcome
You could reverse the comparison (equal instead of unqual) and return the negated result of some.
const
array1 = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }],
array2 = [{ id: 1 }, { id: 3 }],
array3 = array1.filter(entry1 => !array2.some(entry2 => entry1.id === entry2.id));
// ^ ^^^
console.log(array3);
Nina's answer is a good start but will miss any unique elements in array 2.
This extends her answer to get the unique elements from each array and then combine them:
const
array1 = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }],
array2 = [{ id: 1 }, { id: 3 }, { id: 5 }],
array3 = array1.filter(entry1 => !array2.some(entry2 => entry1.id === entry2.id)),
array4 = array2.filter(entry1 => !array1.some(entry2 => entry1.id === entry2.id)),
array5 = array3.concat(array4);
console.log(array5);

How to extend array object by another array using Underscore.JS [duplicate]

This question already has answers here:
Combine two arrays of objects using underscore
(4 answers)
Closed 5 years ago.
I have below list objects:
Object 1:
[{
empId: 1,
name: AAA,
schoolId: 1
}, {
empId: 2,
name: BBB,
schoolId: 2
}]
And Object 2:
[{
schoolId: 1,
schoolName: SchoolA
}, {
schoolId: 2,
schoolName: SchoolB
}]
In both objects Object1 and Object2, SchoolId is common field. Which can be accessed as a mapping field.
Now I using _.extend method of UnderscoreJS I want to achieve below object:
Output:
[{
empId: 1,
name: AAA,
schoolId: 1,
school: SchoolA
}, {
empId: 2,
name: BBB,
schoolId: 2,
school: SchoolB
}]
Can you please suggest how can I achieve this ? Thanks
Create an index (arr1Index) by schoolId of 1st array using _.indexBy(), then _.map() the 2nd array, and create a new object that extends the current object, with an object with the same schoolId from the arr1Index:
var arr1 = [{"empId":1,"name":"AAA","schoolId":1},{"empId":2,"name":"BBB","schoolId":2}];
var arr2 = [{"schoolId":1,"schoolName":"SchoolA"},{"schoolId":2,"schoolName":"SchoolB"}];
var arr1Index = _.indexBy(arr1, 'schoolId');
var result = _.map(arr2, function(o) {
return _.extend({}, o, arr1Index[o.schoolId]);
});
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
You can combine each and findWhere as below.
var d1 = [{
empId: 1,
name: "AAA",
schoolId: 1
}, {
empId: 2,
name: "BBB",
schoolId: 2
}];
var d2 = [{
schoolId: 1,
schoolName: "SchoolA"
}, {
schoolId: 2,
schoolName: "SchoolB"
}];
var output = _.each(d1, function(obj) {
obj.school = _.findWhere(d2, {
schoolId: obj.schoolId
}).schoolName;
});
console.log(output);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
You can use _extend and _find
var arr1 = [{"empId":1,"name":"AAA","schoolId":1},{"empId":2,"name":"BBB","schoolId":2}];
var arr2 = [{"schoolId":1,"schoolName":"SchoolA"},{"schoolId":2,"schoolName":"SchoolB"}];
var output = _.each(arr1, function(a1) {
_.extend(a1, _.find(arr2, function(a2) {
return a2.schoolId == a1.schoolId;
}))
});
console.log(output)
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
You can do it this way (Note: This solution expects that we have two arrays with the same length and the N-th element of the first array should be extended with the N-th element of the second array etc.):
var arrayOne = [{
empId: 1,
name: 'AAA',
schoolId: 1
}, {
empId: 2,
name: 'BBB',
schoolId: 2
}];
var arrayTwo = [{
schoolId: 1,
schoolName: 'SchoolA'
}, {
schoolId: 2,
schoolName: 'SchoolB'
}];
var result = _.map(arrayOne, function(value, index) {
return _.extend({}, value, arrayTwo[index])
})
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
And one addition remark - with Lodash, this problem solves more concisely:
_.zipWith(arrayOne, arrayTwo, _.assign) // ==> returns what you need
Example with Lodash

Categories