How to merge two arrays to make an object [duplicate] - javascript

This question already has answers here:
Create an object from an array of keys and an array of values
(9 answers)
Closed 1 year ago.
consider i have an array say
let arr1=["john","Bruce","Clent"];
and
let arr2=[55,33,22];
Then how can i make an object out of this in javascript
object should look like:{"john":55,"Bruce":33,"Clent":22};
it should take arr1 as object's keys and arr2 as object'values

You can just loop the array, but use the index to match the key and value.
const arr1=["john","Bruce","Clent"];
const arr2=[55,33,22];
const obj = {};
arr1.forEach((val, i) => {
obj[val] = arr2[i];
});

Related

array.push() and splite in Array of arrays [duplicate]

This question already has answers here:
Split array into chunks
(73 answers)
Closed 6 days ago.
This post was edited and submitted for review 6 days ago.
I'm using arrayofArrays[0].push() inside a for loop in order to add an Object to the Array0 inside arrayofArrays.
Now I'd like that when Array0 has reached 2 element, the next element will be pushed to Array1, in order to achieve this situation:
var arrayofArrays = [[Obj0,Obj1],[Obj2,Obj3],[Obj4,Obj5], ...];
Sample code:
var arrayofArrays = [[]];
for(data in Data){
var Obj = {"field1":data[0], "field2":data[1], "field3":data[2] }
arrayofArrays[0].push(Obj); // need to pass to arrayofArrays[1] when arrayofArrays[0] has 2 Obj...
}
(I don't need to split an existing array, I'm adding Object to an array, and want them to split in sub-arrays while adding them)
Here is a functional programming approach to your question to unflatten an array:
const arr = Array.from(Array(6).keys()); // [0, 1, 2, 3...]
let t;
let arrOfArr = arr.map((v, idx) => {
if(idx % 2) {
return [t, v];
} else {
t = v;
return null;
}
}).filter(Boolean);
console.log({
arr,
arrOfArr,
});
Note: Array.from(Array(6).keys()) is just for demo. Replace this with any array of objects you like

JS. Clone object but prefix all values [duplicate]

This question already has answers here:
How to add prefix to array values?
(5 answers)
Closed 7 months ago.
Let's say there's an object with string values:
const A = { key_a1: "value_a1", key_a2: "value_a2" };
What is the way to clone this object and add some prefix to the values? So I want to convert object A into object B that looks next:
const B = { key_a1: "prefix_value_a1", key_a2: "prefix_value_a2" };
I know about copy syntax like const B = { ...A } but that does not allow to modify values.
You can use Object.entries to turn the keys and values of the original object into an array, and reduce to create a new Object with the same keys of the original object with a prefix.
const A = { key_a1: "value_a1", key_a2: "value_a2" };
const B = Object.entries(A).reduce((acc, [key, value]) => ({
...acc,
[`prefex_${key}`]: value
}), {})
console.log(B)
You can loop over it's values, like:
Object.values(A).map(i => `prefix_${i}`)

Combine items after mapping from an array to a single object [duplicate]

This question already has answers here:
Flatten array with objects into 1 object
(12 answers)
Closed 2 years ago.
Can you please help me to create object out of array of objects?
Array to convert arr = [{name:'Ryan'}, {surname:'raynold'}]
required output finalObj = {name:ryan, surname:raynold}
I tried to get the result by doing
let objectArr = Object.assign({}, arr);
but result was like this
{ 0: {shoulder: "14"}, 1:{neck: ""} }
This is a good case for Object.assign.
let arr = [{name:'Ryan'}, {surname:'raynold'}]
let finalObj = Object.assign({}, ...arr);
console.log(finalObj);
Object.assign can take multiple objects as arguments, and so you can spread those objects from your input array. The first argument represents the object in which the others are merged.
You could do it with a array reduce like this:
let finalObj = arr.reduce((acc, cur) => ({...acc, ...cur}), {})

JavaScript scope: preserve object in array in function [duplicate]

This question already has answers here:
How to copy JavaScript object to new variable NOT by reference? [duplicate]
(2 answers)
Closed 3 years ago.
I am using .map() on an array inside a function. I am not modifying the array itself (arr = arr.map(...)), but rather creating a new array (var arr2 = arr.map(...)).
Yet, this still modifies the original arr outside my function (which I don't want). How can I preserve?
var arr = [{prop: 1}];
myFunction(arr);
console.log(arr[0].prop); // returns 2, I want it to return 1
function myFunction(arr) {
var arr2 = arr.map(obj => {
obj.prop = 2;
return obj;
});
console.log(arr[0].prop); // returns 2
}
It modifies based on its reference. If you want to create a new object and modify its properties then you need to use Spread Syntax. Read the documentation:
Spread syntax allows an iterable such as an array expression or string
to be expanded in places where zero or more arguments (for function
calls) or elements (for array literals) are expected, or an object
expression to be expanded in places where zero or more key-value pairs
(for object literals) are expected.
You can try the following:
var arr = [{prop: 1}];
myFunction(arr);
function myFunction(arr) {
var arr2 = arr.map(obj => {
let copyObj = {...obj};
copyObj.prop = 2;
return copyObj;
});
console.log(arr[0].prop);
console.log(arr2[0].prop);
}

how can i simplify this return statement? [duplicate]

This question already has answers here:
ECMAScript 6 arrow function that returns an object
(6 answers)
Closed 3 years ago.
is it possible simplify .map's return statement? I want to add key for each element in the array, and transform arr to array of object. thanks!
let arr = ['c:/a.txt', 'b:/c.txt', 'd:/e.txt'];
let arrObj = arr.map((file) => return {path: file});
You could use a short hand property.
let arr = ['c:/a.txt', 'b:/c.txt', 'd:/e.txt'],
arrObj = arr.map(path => ({ path }));
console.log(arrObj);

Categories

Resources