How to reverse reformatting objects into an array Javascript - javascript

let arr = [{key: 1, value: 10},
{key: 5, value: 20}]
let reformatArr = arr.map(obj => {
let tmp = {};
tmp[obj.key] = obj.value
return tmp;
});
//reformatArr is [{1: 10}, {5: 20}]
How can I reverse this process to its original format?I'm asking because I'm reformatting to send to my backend and want to reformat back when the data is returned.

You can destructure the first element of Object.entries for each object.
let reformatted = [{1: 10}, {5: 20}];
let res = reformatted.map(obj => {
const [[key, value]] = Object.entries(obj);
return {key,value};
});
console.log(res);

Related

How to split an array into smaller arrays every time a specific value appears JavaScript?

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 ] ]

Return a new array of objects with same values grouped by qauntity/length

So i currently have an array like this:
const allMeats = ['Bacon','Bacon','Bacon', 'Steak', 'Lettuce', 'Cabbage','Cabbage','Cabbage','Steak', 'Veal']
I would like to morph the array so that it becomes an array of objects with key/vals that determine the value of the duplicates.
Currently i have got
const meatsGrouped = allMeats.reduce(
(acum, cur) => Object.assign(acum, { [cur]: (acum[cur] || 0) + 1 }),
[],
);
however this code turns the array int this:
[Bacon: 3, Steak: 2, Lettuce: 1, Cabbage: 3, Veal: 1]
when ideally i want it to look like this:
[{Bacon: 3}, {Steak: 2}, {Lettuce: 1}, {Cabbage: 3}, {Veal: 1}]
Can any1 please tell me what i'm doing wrong/missing?
You could do it using reduce and map method.
const allMeats = [
'Bacon',
'Bacon',
'Bacon',
'Steak',
'Lettuce',
'Cabbage',
'Cabbage',
'Cabbage',
'Steak',
'Veal',
];
const ret = Object.entries(
allMeats.reduce((prev, c) => {
const p = prev;
const key = c;
p[key] = p[key] ?? 0;
p[key] += 1;
return p;
}, {})
).map(([x, y]) => ({ [x]: y }));
console.log(ret);
You can do the following using reduce method,
let allMeats = ['Bacon','Bacon','Bacon', 'Steak', 'Lettuce', 'Cabbage','Cabbage','Cabbage','Steak', 'Veal'];
let res = allMeats.reduce((prev, curr) => {
const index = prev.findIndex(item => item.hasOwnProperty(curr));
if(index > -1) {
prev[index][curr]++;
}else {
prev.push({[curr]: 1});
}
return prev;
}, []);
console.log(res);

Array split into 2 and map the corresponding objects and put them in the resultant array

I have an array of array of objects similar to this:
arr = [{
val: 1,
ts: 123
}, {
val: 2,
ts: 125
}, {
val: 3,
ts: 120
}, {
val: 4,
ts: 113
}, {
val: 5,
ts: 117
}, {
val1: 6,
ts: 143
}, {
val1: 7,
ts: 193
}, {
val1: 8,
ts: 187
}, {
val1: 9,
ts: 115
}, {
val1: 10,
ts: 116
}]
The length of the array is always an even number. Now basically I'd like to split them in 2 halves
split1 = [{ val:1}, {val :2}, ......{val:5}]
split2 = [{val1:6},{val1:7},.......{val1:10}]
Now I have to map over these arrays and combine their fields(first item of array1 with first item of array2 and so on) into one single object and add an extra id to it such that result will look like
final = [{val:1, val1:6 , id:1} , {val:2, val1:7,id:3} , {val:3, val1:8,id:3},{val:4, val1:9,id:4},{val: 5, val1:10, id:5}]
This should hold for all arrays of even length and I want to make it a dynamic one. Keys will never be repeated inside source array
What I have tried is:
var res= a.splice(0, arr.length/2);
var c = a.map((val, ind) => { {val, res[ind]} })
Can someone guide here?
You can try this solution
const arr = [{ val: 1},{val: 2},{val: 3}, {val: 4} , {val:5},{ val1: 6},{val1: 7},{val1: 8}, {val1: 9} , {val1:10}]
const split = arr => [arr.slice(0, arr.length/2), arr.slice(arr.length/2, arr.length)]
const splitedArr = split(arr);
const merge = arr => {
const merged = []
for(let i = 0; i < arr[0].length; i++){
let newObj = {...arr[0][i], ...arr[1][i], id:(i+1)}
merged.push(newObj);
}
return merged;
}
const mergedArr = merge(splitedArr);
console.log(mergedArr);
You're quite close, some minor fixes
wrap map function implicit return with () instead of {}
for adding computed value you need to assign key name explicitly
need to destructure val or need to access val.val
const arr = [{ val: 1}, {val: 2}, {val: 3}, {val: 4}, {val: 5}, {val1: 6}, {val1: 7}, {val1: 8}, {val1: 9}, {val1: 10}];
const firstHalf = arr.slice(0, arr.length / 2);
const secondHalf = arr.slice(arr.length / 2);
const final = secondHalf.map((val, ind) => ({
...val,
...firstHalf[ind],
id: ind,
}))
console.log(final);
I have tried
var res= a.splice(0, arr.length/2);
var c = a.map((val, ind) => { {val, res[ind]} })
You're quite close. To make the map callback syntactically valid and create the desired object, it should be
var res = a.splice(0, arr.length/2);
var c = a.map((val, ind) => {
return {val: val.val, val1: res[ind].val1, id: ind+1};
})
or
var c = a.map((val, ind) => {
return Object.assign({id: ind+1}, val, res[ind]);
})

Convert an array of keys into an object of key-value pairs

I know how to convert this:
const keys = [1, 2, 3];
To this:
[{key: 1, val: "q"}, {key: 2, val: "w"}, {key: 3, val: "e"}]
With a single mapping statement:
keys.map((x, i) => ({key: x, val: "qwe".charAt(i)}));
But I would actually like to get this:
{1: "q", 2: "w", 3: "e"}
Is there a neat way to do this in a single statement similar to the one above?
You can use reduce:
keys.reduce((accumulator, value, index) => { accumulator[index] = "qwe".charAt(index); return accumulator; }, {})
Ahhh, got it:
const objects = Object.assign({}, ...keys.map((x, i) => ({[x]: "qwe".charAt(i)})));
Though I would be happy to hear other suggestions as well as any notes on this one...
You can use reduce, and empty object as the initial value for the accumulator and insert property-value pairs on it:
const keys = [1, 2, 3];
let result = keys.reduce((obj, key, idx) => { obj[key] = 'qwe'[idx]; return obj }, {});
console.log(result)
Here is my solution.
const keys = [1, 2, 3];
const vals = "qwe";
const result = keys.reduce((prev, cur, idx) => ({
...prev,
[cur]: vals[idx]
}), {});

Merge array into array of objects

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)

Categories

Resources