convert array of obj to array of array in JavaScript - javascript

I am learning array filter,reduce and map methods. while doing some exercises I got struct. I have array of object like this
var p=[
{
"key": "a",
"value": 4
},
{
"key": "b",
"value": 3
},
{
"key": "c",
"value": 3
},
{
"key": "d",
"value": 6
},
{
"key": "e",
"value": 1
}
]
and this what I did
var column=p.reduce((accumulator, currentValue, currentIndex, array)=>{
var arr=[];
arr[currentValue.key]=currentValue.value;
console.log(accumulator)
return (accumulator.push(arr));
},[])
console.log(column)
and I am expecting array like this
[['a',4],['b',3],['c',3],['d',6],['e',1]]
after first iteration I got this error:
accumulator.push is not a function
I don't know what I am doing wrong.

Getting [['a',4],['b',3],['c',3],['d',6],['e',1]]
Using .reduce
This is what you've used in your code. The problem with your code is that your accessing an index that doesn't exist in arr, because on the previous line you set arr to an empty array. You don't need to have the array arr inside the reduce loop. You should push the value directly to the accumulator
The reduce() method applies a function against an accumulator
const res = p.reduce((acc, curr) => {
acc.push([curr['key'], curr['value']]);
return acc;
}, []);
const p = [ {"key": "a", "value": 4}, {"key": "b", "value": 3}, {"key": "c", "value": 3}, {"key": "d", "value": 6}, {"key": "e", "value": 1} ];
const res = p.reduce((acc, curr) => {
acc.push([curr['key'], curr['value']]);
return acc;
}, []);
console.log(res)
//[['a',4],['b',3],['c',3],['d',6],['e',1]]
Using .map
You can also achieve this same result using a the .map method instead:
The map() method creates a new array with the results of calling a provided function on every element in the calling array.
const res = p.map(e => [e['key'], e['value']]);
const p = [ {"key": "a", "value": 4}, {"key": "b", "value": 3}, {"key": "c", "value": 3}, {"key": "d", "value": 6}, {"key": "e", "value": 1} ];
const res = p.map(e => [e['key'], e['value']])
console.log(res)
//[['a',4],['b',3],['c',3],['d',6],['e',1]]
Getting { 'a': 4, 'b': 3, 'c': 3, 'd': 6, 'e': 1 }
You can use objects instead of having an array for each key/value pairs. This way you can assign a value to a key and get the desired result:
{key: value, ...}
In your case:
{ 'a': 4, 'b': 3, 'c': 3, 'd': 6, 'e': 1 }
Using .reduce
You could do this with the .reduce method:
const obj = p.reduce((acc, curr) => {
acc[curr['key']] = curr['value'];
return acc;
}, {});
const p = [ {"key": "a", "value": 4}, {"key": "b", "value": 3}, {"key": "c", "value": 3}, {"key": "d", "value": 6}, {"key": "e", "value": 1} ];
const obj = p.reduce((acc, curr) => {
acc[curr['key']] = curr['value'];
return acc;
}, {});
console.log(obj)
Using .forEach
Or with a simple .forEach loop:
The forEach() method executes a provided function once for each array element.
let obj = {};
p.forEach(e => obj[e['key']] = e['value']);
const p = [ {"key": "a", "value": 4}, {"key": "b", "value": 3}, {"key": "c", "value": 3}, {"key": "d", "value": 6}, {"key": "e", "value": 1} ];
let obj = {};
p.forEach(e => obj[e['key']] = e['value']);
console.log(obj);

Your result will be an array of objects, not an array of arrays. While you can fix your implementation to work with reduce() it is much simpler to do it with map():
var new_p = p.map(obj => {{[obj.key]: obj.value}});
If you want a single object instead an array of objects, you can use reduce():
var new_p p.reduce((acc, obj) => {
acc[obj.key] = obj.value;
return acc;
}, {});
This assumes that all of the keys are unique. If any key is repeated, you will only get the last value for that key.

You can use map to loop thru the array and return the new object.
var p = [{"key":"a","value":4},{"key":"b","value":3},{"key":"c","value":3},{"key":"d","value":6},{"key":"e","value":1}];
var result = p.map(({key,value}) => ({[key]:value}));
console.log(result);
If you want to create a new object, you can use Object.assign() and map()
var p = [{"key":"a","value":4},{"key":"b","value":3},{"key":"c","value":3},{"key":"d","value":6},{"key":"e","value":1}];
var result = Object.assign(...p.map(o => ({[o.key]:o.value})));
console.log( result );
Doc: map(), Object.assign()

You can use Array.prototype.map() combined with Object.values()
Code:
const p = [{"key": "a","value": 4},{"key": "b","value": 3},{"key": "c","value": 3},{"key": "d","value": 6},{"key": "e","value": 1}];
const result = p.map(o => Object.values(o));
console.log(result);

Related

create and push key value object in array

I have an array :
const data = [{"label": "a", "value": 4}, {"label": "b", "value": 1}, {"label": "c", "value": 2}]
I want to create a new array of objects where I have to give key and value in it.
For eg,:
const newArr = [{1,4},{2,1},{3,2}]
here first item of an object is the key, which has to increase as the number of objects increase, and second item is the value from data.
const data = [{"label": "a", "value": 4}, {"label": "b", "value": 1}, {"label": "c", "value": 2}];
const out = data.map((item, index) => [index + 1, item.value]);
console.log(out);
I hope this is your solution:
const data = [
{
label: 'a',
value: '4'
},
{
label: 'b',
value: '1'
},
{
label: 'c',
value: '2'
},
]
const newArrOfObj = data.reduce((arr, current, index)=> [...arr, {[index+1]:current.value}], []);
console.log(newArrOfObj) //[ { 1: '4' }, { 2: '1' }, { 3: '2' } ]
To push an object into an array, call the push() method, passing it the object as a parameter. For example, arr.push({name: 'Tom'}) pushes the object into the array. The push method adds one or more elements to the end of the array.
index.js
let arr = [];
const obj = {name: 'Tom'};
arr.push(obj);
console.log(arr); // 👉️ [{name: 'Tom'}]

Swap array keys with inner object value

I have this array which holds objects;
let arr = [
{
"id": 1,
"level": "2",
},
{
"id": 2,
"level": "3",
}
]
By default the array has keys starting from 0 and it looks like this:
[
0: {id: 1, level:2},
1: {id: 2, level:3}
]
How can I transform it so that the keys are the values of the property 'level'?
It should look like this:
[
2: {id:1, level:2},
3: {id:1, level:3}
]
So far I have tried this but it doesn't remove the original keys:
arr.map((v, k) => ({[v.level]: v}));
So I have something like this:
[
0: {2:
{id: 1, level:2}
},
1: {3:
{id: 2, level:3}
}
]
You need to populate a new array using reduce:
arr.reduce((prev, curr) => { prev[curr.level] = curr; return prev }, [])
I think I prefer the reduce method, but you could also construct an "array-like" (i.e. an object with numeric keys and a length property) and pass it to Array.from
const maxIdx = Math.max(...arr.map(v => parseInt(v.level, 10)))
const arrLen = maxIdx + 1;
const arrayLike = {
...Object.fromEntries(arr.map(v => [v.level, v])),
length: arrLen
};
const mappedArray = Array.from(arrayLike);
For output of
[undefined, undefined, {
"id": 1,
"level": "2"
}, {
"id": 2,
"level": "3"
}]

Add parameters from one array of objects to enother by identifier

I have two array of objects:
`let arr1 = [
{"var1":1, "id": 1},
{"var2":2, "id": 2},
{"var3":3, "id": 3}]
`let arr2 = [
{"someVal":1, "data":123, "id": 1},
{"someVal":2, data":456, "id": 2}]
I need to add in to objects in 'arr1' parameters someVal from objects in arr2 by id's.
Result should be
`let arr1 = [
{"var1":1, "id": 1, "someVal":1},
{"var2":2, "id": 2, "someVal":1},
{"var3":3, "id": 3}]
Would that work for you?
const arr1 = [{"var1":1,"id":1},{"var2":2,"id":2},{"var3":3,"id":3}],
arr2 = [{"someVal":1,"id":1},{"someVal":2,"id":2}]
result = arr1.map(o => {
const someVal = arr2.find(({id}) => o.id == id)?.someVal
return {...o, ...(someVal ? {someVal} : {})}
})
console.log(result)
.as-console-wrapper{min-height:100%;}
You could use two forEach loops to add the corresponding values to arr1.
let arr1 = [
{"var1":1, "id": 1},
{"var2":2, "id": 2},
{"var3":3, "id": 3}]
let arr2 = [
{"someVal":1, "id": 1},
{"someVal":2, "id": 2}]
arr1.forEach(elem_arr1 => {
arr2.forEach(elem_arr2 => {
if(elem_arr1.id == elem_arr2.id){
elem_arr1["someVal"]= elem_arr2.someVal
}
})
})
console.log(arr1)
arr1.forEach((element) => {
arr2.map(item => {
if(element.id == item.id)
element.someVal = item.someVal;
})
});
you can use forach and object.assign to achieve this
let arr1 = [{"var1":1, "id": 1},{"var2":2, "id": 2},{"var3":3, "id": 3}]
let arr2 = [{"someVal":1, "data":123, "id": 1},{"someVal":2, "data":456, "id": 2}]
arr1.forEach(o=>{arr2.forEach(y=>{ if(o.id==y.id) Object.assign(o,y)})})
console.log(arr1)

How to compare 2 arrays, return the keys from matches from the array to rewrite the keys in first array

I have 2 Arrays:
const firstArray = ["A", "B", "1", "2", "F", "89", "8", "K"];
const inputArray = ["1", "B", "F", "A", "89"];
And with
for (const index of firstArray.keys()) {
console.log(index);
}
I get the keys from my Array: 0, 1, 2, 3, 4, 5, 6, 7, 8
And with
for (const index of inputArray .keys()) {
console.log(index);
}
I get the keys from my input array: 0, 1, 2, 3, 4
I use this to compare and check if all elements are in firstArray:
const foundedArray = inputArray.filter(element => firstArray.includes(element));
All fine till here, but now I need to get the keys from firstArray into my inputArray that they fit to the same matching values from firstArray.
I need get the keys from firstArray into my input array:
Value ["1", "B", "F", "A", "89"];
Keys 2, 1, 4, 0, 5
Im stucking here how can I write this.
playground: https://jsfiddle.net/alaber/u792gdfa/
thank you!
inputArray.map(it => firstArray.indexOf(it))
Using indexOf you can get the position of a certain value innthe array.
For getting a reordered array, you could count the values of inputArray and filter firstArray by checking the leftover count and decrement the count.
const
firstArray = ["A", "B", "1", "2", "F", "89", "8", "K"],
inputArray = ["1", "B", "F", "A", "89"],
count = inputArray.reduce((count, value) => {
count[value] = (count[value] || 0) + 1;
return count;
}, {}),
result = firstArray.filter(value => count[value] && count[value]--);
console.log(result);

Best way to dynamically add items from an array to an object as new values

I'm trying to achieve something like this:
let obj = [
{"id": "1"},
{"id": "2"},
{"id": "3"}
]
const arr = ["a", "b", "c"];
obj = addAtoO(arr, obj); // expected outcome: obj = [{"id": "1", "text": "a"}, {"id": "2", "text": "b"}, {}]
In words: dynamically add values from an array to an object as new values.
Here's what I'm trying:
const addAtoO = (a, o) => {
o.map((i) => {
console.log(Object.keys(i));
// a.forEach((e) => {
// console.log(e);
// });
i['text'] = 'something'; // just add text for testing
});
return o;
};
obj = addAtoO(arr, obj);
console.log('result:');
console.log(obj);
But it seems like there must be a better way.
Thank you so much guys. All your solutions are correct. I had to mark one so I picked the one that is the closest to this specific question.
You can use map as you are using , & use it's index to get the value from arr array and create a new object with values from obj & arr
let obj = [{
"id": "1"
},
{
"id": "2"
},
{
"id": "3"
}
]
const arr = ["a", "b", "c"];
let output = obj.map(function(item, index) {
return Object.assign({}, item, {
text: arr[index]
})
})
console.log(output)
Else you can also use forEach and mutate the original obj array
let obj = [{
"id": "1"
},
{
"id": "2"
},
{
"id": "3"
}
]
const arr = ["a", "b", "c"];
obj.forEach(function(item, index) {
item.text = arr[index]
})
console.log(obj)
The way you are using addAtoO suggests that you don't care about altering the original objects. If that's the case, then a simple forEach will do:
const addAtoO = (arr, obj) => arr.forEach((t, i) => obj[i].text = t);
addToO alters the original array of objects obj, so it doesn't return anything.
Example:
const addAtoO = (arr, obj) => arr.forEach((t, i) => obj[i].text = t);
let obj = [ {"id": "1"}, {"id": "2"}, {"id": "3"}];
const arr = ["a", "b", "c"];
addAtoO(arr, obj);
console.log(obj);
You can use .map() like this:
const arr1 = [
{"id": "1"},
{"id": "2"},
{"id": "3"}
]
const arr2 = ["a", "b", "c"];
const merge = (a1, a2) => a1.map((o, i) => Object.assign({}, o, {text: a2[i]}));
console.log(merge(arr1, arr2));
.as-console-wrapper { max-height: 100% !important; top: 0; }
For more flexibility, i suggest to use a key for the function as well as parameter.
const addTo = (objects, values, key) =>
objects.map((o, i) => Object.assign({}, o, { [key]: values[i] }));
console.log(addTo([{ id: "1" }, { id: "2" }, { id: "3" }], ["a", "b", "c"], 'text'));
If you like to mutate the given objects, just remove the empty object from Object.assign.
const addTo = (objects, values, key) =>
objects.map((o, i) => Object.assign(o, { [key]: values[i] }));
var objects = [{ id: "1" }, { id: "2" }, { id: "3" }];
addTo(objects, ["a", "b", "c"], 'text');
console.log(objects);
There is no need to make things complicated. Just use a forEach.
let obj = [{
"id": "1"
},
{
"id": "2"
},
{
"id": "3"
}
]
const arr = ["a", "b", "c"];
obj.forEach((object, index) => {
object.text = arr[index]
})
console.log(obj)

Categories