Add values from one object to another - javascript

const a1 = [{x:1}, {x:2}],
const a2 = [{y:1}, {y:2}]
I want to achieve final result as:
a = [{x:1,y:1}, {x:2,y:2}]
how do I do this by map method.

const a = a1.map((item, index) => {
return [a1[index], a2[index]];
});

const a1 = [{
x: 1
}, {
x: 2
}];
const a2 = [{
y: 1
}, {
y: 2
}];
(function(a1, a2) {
const ret = a1.map((e, i) => ({ ...e,
...a2[i]
}))
console.log(ret)
})(a1, a2);

I don't know why you want to use map function, maybe is better to use other array methods for better performance and readability. But in this case if you want to use map you can iterate one of the arrays and create for each element ("e") an object, adding to it the corresponding position/key in the other array and the current one. Something like this:
const a = a1.map((e, i) => ({...e, ...a2[i]}))

Related

how to get array according to conditions in javascript

My array comes like this
var data=[{PRODUCT : P1}, {PRODUCT: P2}]
I wantt to convert this into [P1, P2].
Sometimes my array comes like this
var data=[{ITEM: I1, QUANTITY:1}, {ITEM: I2, QUANTITY:2}]
I wantt to convert this into [I1, I2].
so can we make a common function, where I just want to extract particular value of array and make a new array.
p.s. Thank you in advance
I tried to write the logic like this:
data.map((d, index) => { var result= [];
result.includes(d[0]); })
but it,s not dynamic
You could define a function which will always get the first value of the first object key, this should satisfy your needs based on the above
var data1 = [{
ITEM: 'I1',
QUANTITY: 1
}, {
ITEM: 'I2',
QUANTITY: 2
}]
var data2 = [{
PRODUCT: 'P1'
}, {
PRODUCT: ' P2'
}]
function getArrayOfValues(list) {
return list.reduce((acc, x) => {
const firstValue = Object.values(x)[0];
acc.push(firstValue)
return acc;
}, [])
}
const result1 = getArrayOfValues(data1)
console.log(result1)
const result2 = getArrayOfValues(data2)
console.log(result2)
function getProductOrItem(list) {
return list.reduce((accumulator, obj) => {
if (obj.PRODUCT) {
accumulator.push(obj.PRODUCT);
} else if (obj.ITEM) {
accumulator.push(obj.ITEM);
}
return accumulator;
}, [])
}
you can iterate through your array with map() method and inside it extract the value of a first entity of an object in your array and simply get a new array with all values:
const data1 =[{PRODUCT : 'P1'}, {PRODUCT: 'P2'}]
const data2 = [{ITEM: 'I1', QUANTITY: 1}, {ITEM: 'I2', QUANTITY: 2 }]
const transformValuesOfArray = (arrayToTransform) =>
arrayToTransform.map(value => {
const firstObjectValue = Object.values(value)[0]
return firstObjectValue
})
console.log(transformValuesOfArray(data1))
console.log(transformValuesOfArray(data2))

Two object arrays: merge with same key

I have two object arrays. I want to merge with key with value
var a = [{"fit":["34","32","30","28"],"size":["x"]}]
var b = [{"size":["s","m","xl"],"fit":["36"]}]
Expected Output should be
Obj=[{"fit":["34","32","30","28","36"],"size":["x,"s","m","xl"]}]
My Code is
let arr3 = [];
b.forEach((itm, i) => {
arr3.push(Object.assign({}, itm, a[i]));
});
alert(JSON.stringify(arr3))
it gives [{"size":["x"],"fit":["34","32","30","28"]}] which wrong.
Use Array.reduce().
// Combine into single array (spread operator makes this nice)
const myArray = [...a, ...b];
// "reduce" values in array down to a single object
const reducedArray = myArray.reduce((acc, val) => {
return [{fit: [...acc.fit, ...val.fit], size: [...acc.size, ...val.size]}];
});
Edit: if you want the reducer to merge objects regardless of what keys and fields it has then you can do by iterating over the keys of the objects and merging them dynamically:
const reducedArray = myArray.reduce((acc, val) => {
const returnObject = {};
for (const eaKey in acc) {
returnObject[eaKey] = [...acc[eaKey], ...val[eaKey]];
}
return [returnObject];
});
If the fields of the objects aren't guaranteed keys then you will need to get even more dynamic in detecting the type of merge and how to do it, but it's possible and I will leave that as an exercise for you to figure out. :)
Note that if there are duplicate values in each of the "fit" and "size" arrays, they will not be deduplicated. You'd have to do that manually as a separate step either with extra logic in the reduce function or afterwards.
combine a and b in a single array then reduce it starting with an array having an object with empty fit and size arrays:
var a = [{ fit: ["34", "32", "30", "28"], size: ["x"] }];
var b = [{ size: ["s", "m", "xl"], fit: ["36"] }];
var obj = [...a, ...b].reduce(
(acc, curr) => {
Object.keys(curr).forEach(k => {
acc[0][k] = [...new Set([...(acc[0][k] || []), ...curr[k]])];
});
return acc;
},
[{}]
);
console.log(obj);
You can create a combine function that takes fit and size from any two objects and merges them.
Use it as a reducer to combine everything.
let combine = ({fit, size}, {fit: fit2, size: size2}) =>
({ fit: [...fit, ...fit2], size: [...size, ...size2] });
let result = [...a, ...b].reduce(combine);
Example:
var a = [{"fit":["34","32","30","28"],"size":["x"]}, {"fit": ["10", "11"], "size":["xxxxxxxxl"]}]
var b = [{"size":["s","m","xl"],"fit":["36"]}];
let combine = ({fit, size}, {fit: fit2, size: size2}) =>
({ fit: [...fit, ...fit2], size: [...size, ...size2] });
let result = [...a, ...b].reduce(combine);
console.log(result);
If you don't want to use the keys directly you could try
const arr3 = b.reduce((carry, current, index) => {
Object.keys(current)
.forEach(key => {
Object.assign(carry, { [key]: Array.prototype.concat.call(current[key], a[index][key])});
});
return carry;
}, {});

Having issue with typescript dictionary

I am building an typescirpt dictionary like that:
const skills = x
.map(y => y.skills)
.flat(1)
.map(z => {
return { [z.id]: { skill: z } };
});
That is the array I am getting by the code above:
{ 7ff2c668-0e86-418a-a962-4958262ee337: {skill: {…}} }
{ c6846331-2e11-45d6-ab8d-306c956332fc: {skill: {…}} }
{ 0fc0cb61-f44d-4fd0-afd1-18506380b55e: {skill: {…}} }
{ 36dc0b74-84ee-4be2-a91c-0a91b4576a21: {skill: {…}} }
Now the issue is I can not access the dictionary by key:
const id = '7ff2c668-0e86-418a-a962-4958262ee337';
const one = myArr.find(x => x === id); // returns undefined
const two = myArr[id]; // returns undefined
Any ideas how to fix?
You can use Object.keys() to get the key of each of your objects. In your case the key of each of your objects is its id. Then use that to check whether it equals x (you search id).
See example below:
const myArr = [
{"7ff2c668-0e86-418a-a962-4958262ee337": {skill: 1}},
{"c6846331-2e11-45d6-ab8d-306c956332fc": {skill: 2}},
{"0fc0cb61-f44d-4fd0-afd1-18506380b55e": {skill: 3}},
{"36dc0b74-84ee-4be2-a91c-0a91b4576a21": {skill: 4}}],
id = "36dc0b74-84ee-4be2-a91c-0a91b4576a21",
one = myArr.findIndex(x => Object.keys(x)[0] === id); // the index of the object which has the search id as its key.
myArr[one] = {newKey: "newValue"}; // set the index found to have a new object
console.log(myArr);
You are now creating an array of objects. I suggest you create an object instead, with your ids as keys
Example:
const skills = x
.map(y => y.skills)
.flat(1)
.reduce((acc, z) => {
acc[z.id] = z;
return acc;
}, {});
Your myArr is going to look something like:
{
'7ff2c668-0e86-418a-a962-4958262ee337': {...}
'c6846331-2e11-45d6-ab8d-306c956332fc': {...},
'0fc0cb61-f44d-4fd0-afd1-18506380b55e': {...},
'36dc0b74-84ee-4be2-a91c-0a91b4576a21': {...}
}
You can then access it the way you intended:
const skill = myArr['7ff2c668-0e86-418a-a962-4958262ee337'];
make use of map that can help,
Map is a new data structure introduced in ES6. It allows you store key-value pairs similar to other programming languages e.g. Java, C#.
let map = new Map();
const skills = x
.map(y => y.skills)
.flat(1)
.map(z => {
map.set(z.Id, { skill: z })
return map;
});
//Get entries
amp.get("7ff2c668-0e86-418a-a962-4958262ee337"); //40
//Check entry is present or not
map.has("7ff2c668-0e86-418a-a962-4958262ee337"); //true

From nested array to array of object

I have a nested array like this
array = [[1, 698],[32, 798],[69, 830],[95, 500]]
I want to have a function that return the result in this format
[
{
id: 1,
score: 698
},
{
id: 32,
score: 798
},
{
id: 69,
score:830
},
..... the rest of the array
]
I did use a for loop but with no success, and I have no idea on how to aproach the situation.
for(var i = 0; i <= array.lenght ; i++){
var obj={}
var res = []
res.push(array[i])
}
You can take the advantage of the power of the ES6 syntax:
var array = [
[1, 698],
[32, 798],
[69, 830],
[95, 500],
];
var res = array.map(([id, score]) => ({id, score}));
console.log(res);
You can use Array.prototype.map() with destructuring assignment:
const array = [[1, 698],[32, 798],[69, 830],[95, 500]];
const result = array.map(([id, score]) => ({id, score}));
console.log(result);
Use array.prototype.map, destructuring and shorthand object litteral:
var array = [[1, 698],[32, 798],[69, 830],[95, 500]];
var result = array.map(([id, score]) => ({id, score}));
console.log(result);
var sampleArray = [[1, 698],[32, 798],[69, 830],[95, 500]];
var finalJson = sampleArray.map(([id, score]) => ({id, score}));
// Final Result
console.log(finalJson);
first you need a function that takes a 2 element array and returns an object
const objBuilder = arr => return { id: arr[0], score: arr[1] }
you will want to add error handling, but thats the basic idea.
Next you want to iterate over the array of arrays transforming each value (2 element array) into an object. Thats called mapping over values, and js supports it natively
const arrayOfObjects = array.map(objBuilder)
more about map function here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
The answers from a number of people suggesting .map(([id, score]) => ({id, score})) are great. But if you have to do things like this often, you might want to write a reusable function to make this more declarative. For that, something like this might work:
const zipObject = names => values => names.reduce(
(obj, name, idx) => (obj[name] = values[idx], obj), {}
)
const array = [[1, 698], [32, 798], [69, 830], [95, 500]]
console.log(array.map(zipObject(['id', 'score'])))
Note that you could also extend this to
zipAllObjects = names => listsOfValues => listsOfValues.map(zipObject(names))
and just call
zipAllObjects(['id', 'score'])(array)

flatten array of object into an array

const x = [{
name:"abc",
},{
name:"xyz"
}]
how to turn above array of object into an array?
expected output
x = ['abc','xyz']
I know I can do a native loop, use push to a new empty array but I'm looking for one line es2015/es6 or even lodash method
Simply use the map function:
const y = x.map(c => c.name);
const x = [{
name:"abc",
},{
name:"xyz"
}]
const names = x.map(c => c.name);
console.log(names);
Solution in Lodash (very similar to plain js):
const x = [{
name:"abc",
},{
name:"xyz"
}]
const names _.map(x, 'name'); // => ['abc', 'xyz']
Edit
as requested also in plain js
const names = x.map(el => el.name);
or
const names = x.map(function(el) {
return el.name;
});
x = [{
name:"abc",
},{
name:"xyz"
}];
x = x.map(function (value) {
return value.name;
});
Use map()
let res = x.map(o => o.name);

Categories

Resources