How to make the nested items of array to object? - javascript

I have a nested array like this:
var arr = [
['Simcard', 'one'],
['Charge', 'two'],
];
I want to make it like this:
[
{"Simcard": "one"},
{"Charge": "two"},
]
How can I do that?
Here is what I've tried but not exactly the expected result:
let res = Object.keys(x).map((key) => {key: x[key]});

There's a builtin Object.fromEntries that turns a two-element array into an object.
var arr = [
['Simcard', 'one'],
['Charge', 'two'],
];
var desired = [
{"Simcard": "one"},
{"Charge": "two"},
]
var answer = arr.map(entry => Object.fromEntries([entry]));
console.log(answer)

This is not a oneliner, but you could try the following
let res = []
arr.forEach(element => res[element[0]] = element[1])

let res = arr.map(item => ({[item[0]]: item[1]}))

You can use Array#map as follows. I think you biggest challenge was having the key in a variable: so that the word key does not become the key but it's value we use [key] instead.
const arr = [ ['Simcard', 'one'], ['Charge', 'two'] ],
res = arr.map(([key,value]) => ({[key]: value}));
console.log( res );

Related

Replace an object that is inside of array if object id value from another array match

I have this arrays with objects that looks like this:
array1 = [
0:{id:145, value:130000},
1:{id:146, value:103300},
2:{id:147, value:79500},
]
array2 = [
0:{id:145, value:135000}
]
And I want to replace the object inside the array if the id of the object in array2 match with some id of the object in array1
So I expect something like this:
array1 = [
0:{id:145, value:135000},
1:{id:146, value:103300},
2:{id:147, value:79500},
]
I have this code
array1.splice(1, 1, array2[0])
but it returns me this:
array1 = [
0:{id:145, value:135000},
1:{id:145, value:130000},
2:{id:146, value:103300},
3:{id:147, value:79500},
]
Any help I'll appreciate
let array1 = [
{id:145, value:130000},
{id:146, value:103300},
{id:147, value:79500},
]
let array2 = [
{id:145, value:135000},
{id:147, value:135023}
]
array2.map(x => {
let index = array1.findIndex(d=> d.id === x.id)
array1[index] = x
})
console.log(array1)
array2.forEach(i1 => {
const index = array1.findIndex(i2 => i2.id == i1.id);
if(index > -1) {
array1.splice(index, 1, i1);
}
});

How to get same value from array of objects using javaScript?

I have two arrays, my aim is to filter the second array arr2 by the first array arr1, and get only matched values where prid is the same as arr2 id, results should be let filtred = [ {name:'kiwi', color:'red', id:12123},{name:'kiwi', color:'red', id:12123}], how i can ichieve this using filter?
let arr1 = [
{prid:12123},
{prid:12124}
]
let arr2 = [
{name:'kiwi', color:'red', id:12123},
{name:'kiwi2', color:'blue',id:12129},
{name:'kiwi3', color:'green',id:12124}
]
Please note: According to your requirement your expected output is not correct:
You can try using Array.prototype.some() inside Array.prototype.filter() by matching the respective property value (prid of arr1 with id of arr2).
let arr1 = [
{prid:12123},
{prid:12124}
]
let arr2 = [
{name:'kiwi', color:'red', id:12123},
{name:'kiwi2', color:'blue',id:12129},
{name:'kiwi3', color:'green',id:12124}
]
let filtred = arr2.filter(i => arr1.some(j => j.prid == i.id))
console.log(filtred);
You can use Array.prototype.reduce which allows to create another array with different structure
let arr1 = [
{prid:12123},
{prid:12124}
]
let arr2 = [
{name:'kiwi', color:'red', id:12123},
{name:'kiwi2', color:'blue',id:12129},
{name:'kiwi3', color:'green',id:12124}
]
let results = arr2.reduce((accumulator, currentItem) =>{
let itemExists = arr1.findIndex(item => item.prid === currentItem.id);
return itemExists !== -1? accumulator.concat(currentItem): accumulator;
}, []);
console.log(results);

Is there a more elegant way of filtering key/value pairs based on key values? [duplicate]

This question already has answers here:
From an object, extract properties with names matching a test
(4 answers)
Closed 1 year ago.
I have an array of objects like this,
value = [
{"f1_x":1, "f1_y":3, "f2_x": 5},
{"f1_x":2, "f2_y":4, "f2_x": 6}
]
Now, I only want to keep key/value pairs where key ends with _x. So, the above would look like this,
value = [
{"f1_x":1, "f2_x": 5},
{"f1_x":2, "f2_x": 6}
]
I used the following, but is there any more elegant way of doing the same?
var x = value.map(e => {
r = {}
for (const f in e)
if (f.toLowerCase().endsWith("_x"))
r[f] = e[f]
return r
})
You can use Object.prototype.fromEntries and Object.prototype.entries
const value = [
{"f1_x":1, "f1_y":3, "f2_x": 5},
{"f1_x":2, "f2_y":4, "f2_x": 6}
];
const result = value.map((obj) => Object.fromEntries(Object.entries(obj).filter(([key]) => key.endsWith("_x"))));
console.log(result)
Not quite sure if it's any better, but here's a single liner:
let value = [
{"f1_x":1, "f1_y":3, "f2_x": 5},
{"f1_x":2, "f2_y":4, "f2_x": 6}
];
let newValue = value.map(e => Object.fromEntries(Object.entries(e).filter(p => p[0].toLowerCase().endsWith("_x"))));
console.log(newValue);
I can write it like this for a little better readability.
var x = value.map(e => {
let r = {};
let newKeys = Object.keys(e).filter((x) => x.toLowerCase().endsWith("_x"));
newKeys.forEach((x) => r[x] = e[x]);
return r
});
In the following method, you can use Array methods explicitly.
let value = [
{"f1_x":1, "f1_y":3, "f2_x": 5},
{"f1_x":2, "f2_y":4, "f2_x": 6}
]
let filtered = value.map(obj =>
Object.keys(obj).reduce((a, c) => {
c[c.length - 1] === 'x' ? a[c] = obj[c] : null;
return a
}, {})
)
console.log(filtered);

Concat all values inside a map

I've got a constant result like this :
result: Map<string, string[]>
When I do a console.log(result) the output is :
Map {
'toto' => [ 'a-1', 'a-2' ],
'tata' => [ 'b-1', 'b-2' ],
'titi' => [ 'c-1', 'c-2' ],
}
What I want to have, it's a constant globalResult with all values like this:
const globalResult = [ 'a-1', 'a-2','b-1','b-2','c-1','c-2' ]
How can I do this ?
Thanks
You can get map values into an array and then use flat() method on it like:
const myMap = new Map().set('toto', ['a-1', 'a-2']).set('tata', ['b-1', 'b-2'])
const arr = [...myMap.values()].flat()
console.log(arr)
You can use Array.from to covert map values into a flat array
const map = new Map();
map.set('a',11)
map.set('b',22)
map.set('c',33)
const array = Array.from(map.values())
console.log(array)
You could get the values of the properties and flat the arrays.
const
object = { toto: ['a-1', 'a-2'], tata: ['b-1', 'b-2'], titi: ['c-1', 'c-2'] },
array = Object.values(object).flat();
console.log(array);
Use forEach function.
const obj = {
'toto' : [ 'a-1', 'a-2' ],
'tata' : [ 'b-1', 'b-2' ],
'titi' : [ 'c-1', 'c-2' ],
}
const arr = [];
Object.values(obj).forEach(value=>arr.push(...value));
console.log(arr);

How to sort a list on another list in lodash

Gived a list
[
{id:'i1',value:'v1'},
{id:'i3',value:'v3'},
{id:'i4',value:'v4'},
{id:'i2',value:'v2'},
{id:'i5',value:'v5'},
]
and another ordered id list
['i1','i2','i3','i4','i5']
get
[
{id:'i1',value:'v1'},
{id:'i2',value:'v2'},
{id:'i3',value:'v3'},
{id:'i4',value:'v4'},
{id:'i5',value:'v5'},
]
How to do this in lodash?
Use sortBy method and return the id's index position from the iteratee function
let sortedArray = _.sortBy(input, (v) => order.indexOf(v.id))
where
input = [
{id:'i1',value:'v1'},
{id:'i3',value:'v3'},
{id:'i4',value:'v4'},
{id:'i2',value:'v2'},
{id:'i5',value:'v5'},
]
order = ['i1','i2','i3','i4','i5']
Convert Array to Object where key is id for better lookup. Replace each element in ordered list with actual value.
Edge case: the two array has the same elements
const foo = [
{id:'i1',value:'v1'},
{id:'i3',value:'v3'},
{id:'i4',value:'v4'},
{id:'i2',value:'v2'},
{id:'i5',value:'v5'},
];
const ordered = ['i1','i2','i3','i4','i5'];
const fooMap = _.keyBy(f, 'id');
const orderedFoo = ordered.map(id => fooMap[id])
const arr = ['i1','i2','i3','i4','i5'];
const arrObj = [
{id:'i1',value:'v1'},
{id:'i3',value:'v3'},
{id:'i4',value:'v4'},
{id:'i2',value:'v2'},
{id:'i5',value:'v5'}
]
const sortedArr = [];
_.map(arr, a => sortedArr.push(_.find(arrObj, ['id', a])));
console.log(sortedArr)
let arr = ['i1','i2','i3','i4','i5'];
let arrObj = [
{id:'i1',value:'v1'},
{id:'i3',value:'v3'},
{id:'i4',value:'v4'},
{id:'i2',value:'v2'},
{id:'i5',value:'v5'}
]
console.table(arrObj);
arr.map(v => {
arrObj.sort( v1 => { return v1.id == v ? true : false} )
})
console.table(arrObj);

Categories

Resources