I am working in vanilla JavaScript.
I have two arrays of the same length.
Each of them is containing objects.
I need to create one array with objects combined.
How?
So, in code, my input is:
const arr1 = [{name: "John"}, {name: "Peter"}];
const arr2 = [{age: 56}, {age: 22}]
Desirable output:
const arr3 = [{name: "John", age: 56}, {name: "Peter", age: 22}]
I saw solution that ES6 offers, and it goes like this:
const object1 = {
name: 'John'
}
const object2 = {
age: 56
}
const object3 = {...object1, ...object2 }
That works just great! I would like to implement this same solution in this example whit objects in arrays using this spread operator. How? :)
Thank you.
Using Array.prototype.map() and spread syntax:
const arr1 = [{ name: 'John' }, { name: 'Peter' }];
const arr2 = [{ age: 56 }, { age: 22 }];
const arr3 = arr1.map((v, i) => ({ ...v, ...arr2[i] }));
console.log(arr3);
Another option
const arr1 = [{name: "John"}, {name: "Peter"}];
const arr2 = [{age: 56}, {age: 22}];
const result = [];
for(let i = 0; i < arr1.length; i++) result.push(Object.assign(arr1[i], arr2[i]));
console.log(result)
P.S, also as #charlietfl mentioned: if you don't want to mutate objects in arr1 start with empty object ... Object.assign({},arr1[i], arr2[i])
Related
How would you go about splitting an array at the word 'split' and creating smaller sub arrays out of them?
This is what my array looks like right now (but much longer):
const myArray = ['abc', 'xyz', 123, 'split', 'efg', 'hij', 456, 'split'];
This is what I would like it to look like:
const newArray =[['abc', 'xyz', 123], ['efg', 'hij', 456]];
If it helps at all I also have the indexes of the words 'split' in an array like this:
const splitIndex = [3, 7];
You could iterate splitIndex and slice the array until this index.
const
data = ['abc', 'xyz', 123, 'split', 'efg', 'hij', 456, 'split'],
splitIndex = [3, 7],
result = [];
let i = 0;
for (const j of splitIndex) {
result.push(data.slice(i, j));
i = j + 1;
}
console.log(result);
const myArr = ['abc', 'xyz', 123, 'split', 'efg', 'hij', 456, 'split'];
const foo = (arr, key) => {
let temp = [];
const result = [];
arr.forEach(v => {
if (v !== key) {
temp.push(v);
} else {
result.push(temp);
temp = [];
}
})
return result;
}
console.log(foo(myArr, 'split'));
output:
[ [ 'abc', 'xyz', 123 ], [ 'efg', 'hij', 456 ] ]
For example, let's say I have the following:
let data = [{name: "Bob"}, {name: "Alice"}]
let numArr = [12, 34]
I'd like this as the result:
let newData = [{name: "Bob", number: 12}, {name: "Alice", number: 34}]
Using Array#map:
const
data = [{name: "Bob"}, {name: "Alice"}],
numArr = [12, 34];
const newData = data.map((e, i) => ({ ...e, number: numArr[i] }));
console.log(newData);
You can use Symbol.iterator and forEach.
let data = [{name: "Bob"}, {name: "Alice"}];
let numArr = [12, 34];
ns=numArr[Symbol.iterator]();
data.forEach((d)=>d.number=ns.next().value);
document.write(JSON.stringify(data));
You need to define the iterated array outside of the forEach loop, otherwise the definition is re-initiated with every pass, and returns the same value each time.
I'm working with API data and I'm trying to build an object combining multiple arrays of data.
Current Arrays:
let name = [{name: "John"},{name: "Jane"},{name: "Doe",}]
let arr1 = ['bar', 'foo', 'foobar']
let arrX = ...
Desired Outcome:
let desiredOutcome = [
{
name: "John",
arr1: "bar", ...
},
{
name: "Jane",
arr1: "foo", ...
},
{
name: "Doe",
arr1: "foobar", ...
}]
I've been trying to play around with Object.assign() but I haven't had any luck:
var merge = Object.assign(obj, arr1 )
Is there a method or methods I could use?
Use .map() to add each element.
let name = [{name: "John"},{name: "Jane"},{name: "Doe",}]
let arr1 = ['bar', 'foo', 'foobar']
let result = name.map((a,i)=>{a.arr1 = arr1[i]; return a})
console.log(result)
You can do it using Array.map
Try the following:
let name = [{name: "John"},{name: "Jane"},{name: "Doe",}]
let arr1 = ['bar', 'foo', 'foobar'];
var result = name.map((o,i) =>Object.assign({"arr1" : arr1[i]},o));
console.log(result);
For an arbitrary count of arrays, you could take an array with the array of objects and the arrays of values and take short hand properties which preserves the name of the array and the values for adding to the result set with Object.assign.
var names = [{ name: "John" }, { name: "Jane" }, { name: "Doe" }],
arr1 = ['bar', 'foo', 'foobar'],
arrX = [1, 2, 3],
result = [names, { arr1 }, { arrX }]
.reduce((r, o) =>
(([k, a]) => a.map((v, i) => Object.assign({}, r[i], { [k]: v })))(Object.entries(o)[0])
);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Maybe late but I'll provide some additional explanation on how to use .map:
The .map method creates a new array with the results of calling a provided function on every element in the calling array.
The method takes in one callback as argument. The callback itself can take predefined arguments. Here we will use the first two:
currentValue: e
index: i
Basically, the map method works by associating (literally mapping) each element of the looped array (here name) to the given returned value (here {name: e.name, arr1: arr1[i]}). Mapping is just a bijection between two arrays.
Another word on (e,i) => ({name: e.name, arr1: arr1[i]}):
It is the shorthand syntax called arrow function. It is similar to defining the callback function like so:
function(e,i) {
return { name: e.name, arr1: arr1[i] };
}
Full snippet will look like:
const name = [{name: "John"},{name: "Jane"},{name: "Doe",}]
const arr1 = ['bar', 'foo', 'foobar']
const result = name.map((e,i) => ({ name: e.name, arr1: arr1[i] }))
console.log(result)
I have this array:
var arr1 = [
{"user":"dan","liked":"yes","age":"22"},
{"user":"sarah","liked":"no","age":"21"},
{"user":"john","liked":"yes","age":"23"},
];
I'd like to create a new (sub)array of that array, containing only the likes of the users.
so it would look like this:
var arr2 = [
{"dan":"yes"},
{"sarah":"no"},
{"john":"yes"},
];
I tried:
var arr2 =[];
for(var i in arr1){
arr2.push({[i[user]]:i[liked]});
}
it needs a tweak,
ideas?
Use array.map
var arr1 = [
{"user":"dan","liked":"yes","age":"22"},
{"user":"sarah","liked":"no","age":"21"},
{"user":"john","liked":"yes","age":"23"},
];
var arr2 = arr1.map(v => ({ user: v.user, liked: v.liked }));
console.log(arr2);
With your update, although it can be done with array.map, I recommend you use a key-value pair structure instead. You'd need array.reduce.
var arr1 = [
{"user":"dan","liked":"yes","age":"22"},
{"user":"sarah","liked":"no","age":"21"},
{"user":"john","liked":"yes","age":"23"},
];
var arr2 = arr1.reduce((c, v) => (c[v.user] = v.liked, c) , {});
console.log(arr2);
Based on your edit:
arr1 = arr1.map(function(item){
return{
[item.user]: item.liked
}
});
var arr1 = [
{"user":"dan","liked":"yes","age":"22"},
{"user":"sarah","liked":"no","age":"21"},
{"user":"john","liked":"yes","age":"23"},
];
var res = arr1.map(function(o) {
var r = {};
r[o.user] = o.liked;
return r;
});
console.log(res);
Or in recent ECMAScript versions:
var arr1 = [
{"user":"dan","liked":"yes","age":"22"},
{"user":"sarah","liked":"no","age":"21"},
{"user":"john","liked":"yes","age":"23"},
];
var res = arr1.map(o => ( { [o.user]: o.liked } ));
console.log(res);
You could map the deconstructed wanted properties to a new object.
var array1 = [{ user: "dan", liked: "yes", age: "22" }, { user: "sarah", liked: "no", age: "21" }, { user: "john", liked: "yes", age: "23" }],
array2 = array1.map(({ user, liked }) => ({ [user]: liked }));
console.log(array2);
ES5
var array1 = [{ user: "dan", liked: "yes", age: "22" }, { user: "sarah", liked: "no", age: "21" }, { user: "john", liked: "yes", age: "23" }],
array2 = array1.map(function (o) {
var temp = {};
temp[o.user] = o.liked;
return temp;
});
console.log(array2);
Try this
var arr2 =[];
for(var i in arr1){
var obj= {};
obj[arr1[i]['user']] = arr1[i]['liked'];
arr2.push(obj)
}
var arr2=[];
arr1.forEach(function(obj)
{
var temp=new Object();
temp[obj.user]=obj.liked;
arr2.push(temp);
});
I think this is what you want
array.map will help you, for you understanding since map returns a new array based on your logic, The following example is simple and readable
const arr1 = [
{"user":"dan","liked":"yes","age":"22"},
{"user":"sarah","liked":"no","age":"21"},
{"user":"john","liked":"yes","age":"23"},
];
const arr2 = arr1.map(({user, liked}) => ({ [user]:liked }));
console.log(arr2);
if it is an array of objects
var arr1=[{},{},..]
and you have to loop through the objects attributes so you need this
var arr2 =[]
arr1.forEach(element => {
var temp = new Object();
for (var name in element) {
temp[name] = element[name]
}
arr2 .push(temp)
});
now you have arr2 as an other object different from arr1
I have two arrays containing the same elements but in different order, like this:
var arr1 = [{name: 'Bob', age: 24}, {name: 'Mary',age: 45}, {random: props}];
var arr2 = [{name: 'Mary', age:45 }, {name: 'Bob',24}, {other: randomProps}];
In this case of course a simple reverse() would do the trick but it might be an array with 10 objects in a random order.
Since both arrays always contains some common properties (name) I should be able to rearrange one array to match the other based on name.
Any tips on how to go about this?
Maybe something like this then? But this assumes that each object in the array has the name property.
var arr1 = [{name: 'Bob', age: 24}, {name: 'Mary',age: 45}, {random: props}];
var arr2 = [{name: 'Mary', age:45 }, {name: 'Bob',24}, {other: randomProps}];
function sortArray(arr) {
arr.sort(function(a, b) {
return a.name > b.name;
});
}
sortArray(arr1);
sortArray(arr2);
I think you can scan the arranged array and search elements in the second array and put them in a new array.
new_array;
foreach(element in array_ordered)
{
temp = search(element[name], array_unordered);
if(temp != null)
new_array.add(temp);
}