how convert values string into a integer object array by key - javascript

i have this object array:
let arr = [
{
'pippo': '1',
'descrizione': 'ciao'
}
];
and i want convert "1" to 1 by key:
let arr = [
{
'pippo': 1,
'descrizione': 'ciao'
}
];
any solution?
br
Max

You can iterate over the objects and create a new array with the converted number with the help of parseInt().
arr = arr.map(item => {
return {
...item, //copies all items first...
pippo: parseInt(item.pippo) //...then overwrites pippo
}
}

Related

how to change the array format to the object format?

How to use javascript to change the array to the object format? Thanks!
[ "16-282", "16-311", "16-320", "17-275", "17-276" ]
object format:
[{
id: 16,
Options: [282, 311, 320],
},
{
id: 17,
Options: [275, 276],
}]
My Code:
test() {
var option = ["16-282", "16-311", "16-320", "17-275", "17-276"];
var finalResult = option.map((item, index) => ({id: item, Options: item, }));
console.log(finalResult);
},
What you want is a "groupBy" operation using the id as object keys and a new object as values
Solution using Array#reduce() and a Map
var option = ["16-282", "16-311", "16-320", "17-275", "17-276"];
const group = option.reduce((m, c) => {
const [id, val] = c.split('-');
const obj = m.get(id) || { id, options: [] };
obj.options.push(val);
return m.set(id, obj)
}, new Map)
console.log([...group.values()])
.as-console-wrapper {
max-height: 100%!important;
top: 0
}
Lets start with your code:
var finalResult = option.map((item, index) => ({id: item, Options: item, }));
Here you are using .map. It will return an array of n length with parsed output.
Based on your output, you need to group the values based on part that is before -. This can be done in many ways, but I'll use for as its easy to understand:
Idea:
Create an object to hold groups. Object and not array as Objects are key-value pair structure. So your groupId would be key and value will be the value to store.
Now loop over the option array.
For every iteration, split item using hyphen(-). First part is your key and second is your value.
Check if this key exists in group. If yes, push current value to the Options array.
If it does not exists, initialize it with default structure:
{ id: groupKey, Options: [ groupValue ] }
Sample:
var option = ["16-282", "16-311", "16-320", "17-275", "17-276"];
var groups = {};
for (var i = 0; i< option.length; i++) {
var parts = option[i].split('-');
var groupKey = parts[0];
var groupValue = parts[1];
// Check if the groupKey exists in group
if (groups[ groupKey ] !== undefined) {
groups[ groupKey ].Options.push(groupValue)
} else {
groups[ groupKey ] = { id: groupKey, Options: [ groupValue ] }
}
}
console.log(groups)
Now that you have groups, you just need to loop over this object and make an array.
An accumulation of above grouping idea and creating array is as follows:
var option = ["16-282", "16-311", "16-320", "17-275", "17-276"];
const groups = option.reduce((acc, item) => {
const [ id, value ] = item.split('-');
acc[ id ] = acc[ id ] || { id, Options: [ ]};
acc[ id ].Options.push(value);
return acc;
}, {});
const result = Object.values(groups);
console.log(result)
.as-console-wrapper {
top: 0;
max-height: 100vh!important;
}

How to convert array of objects to object made up of only values

I have [ { key1:value1, key2:value2 }, { key3:value3, key4:value4 }, .... ]. I want to convert it to
{ value1: value2, value3: value4 }
Use Array#reduce to accumulate your object-data. Foreach object take from the values the first and add a new property with this name to the accumulated object with the value from the second object-value.
let array = [ { key1:'value1', key2:'value2' }, { key3:'value3', key4:'value4' }];
let res = array.reduce((acc, cur) => {
values = Object.values(cur);
acc[values[0]] = values[1];
return acc;
}, {});
console.log(res);
Assuming the inner objects always have 2 keys:
const arr = [ { key1:'value1', key2:'value2' }, { key3:'value3', key4:'value4' }]
const obj = {};
for (const innerObj of arr) {
const values = Object.values(innerObj);
obj[values[0]] = values[1];
}
console.log(obj) // { value1: 'value2', value3: 'value4' }
Note: you're question assumes an order for the keys in the inner objects, but that may not be guaranteed

how to add key of object in array?

Guys.
I have array like this
array = [{name:"A",data:"..."},{name:"B",data:"..."},{name:"C",data:"..."}]
And I want to edit this array to
array = [ "A":{name:"A",data:"..."},"B":{name:"B",data:"..."},"C":{name:"C",data:"..."}
How could I set object key from its own value?
For getting an object, you could take Object.fromEntries with the mapped key/value pairs
var array = [{ name: "A", data: "..." }, { name: "B", data: "..." }, { name: "C", data: "..." }],
result = Object.fromEntries(array.map(o => [o.name, o ]));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Try this:
console.log(array.map(el => ({[el.name]: el})));
JavaScript array doesn't work that way. An array's index value can only have an increasing numeric indexes([0, 1, ..., n]). If you wan't to create such list you can create the object instead of an array.
const array = [{name:"A",data:"..."},{name:"B",data:"..."},{name:"C",data:"..."}];
const newList = {};
array.forEach(obj => {
newList[obj.name] = obj;
});
console.log({ newList });
In this way you can create the object out of array. You can then loop the object's keys like in arrray using:
Object.keys(newList).forEach((key) => {
console.log(newList[key]);
})
. Hope it helps.
Just do this.
var arr = [{name:"A",data:"..."},{name:"B",data:"..."},{name:"C",data:"..."}]
var output = arr.map(elem => ({[elem.name]: elem}))
console.log(output)

Assign a key number to a key in the object by incrementing count

I have an array of objects . I need to convert the value of the 'key' by incrementing count .
lets say I have an array
const arr1=[{key:'a', val:1},{key:'b',val:2}]
I want to give an incrementing key value to each key
I have tried the below code but couldn't override the count value
let count = 0;
const arr1=[{key:'a', val:1},{key:'b',val:2}]
arr1.map(el => el.key=count+1);
console.log(arr1)
Expected Result :
[ { key: 1, val: 1 }, { key: 2, val: 2 } ]
You could use forEach to loop through the array and update the key based on the index
const array = [ { key: 1, val: 1 }, { key: 2, val: 2 } ]
array.forEach((o, i) => o.key = i+1)
console.log(array)
If you want a new array you could use map like this:
const array = [ { key: 1, val: 1 }, { key: 2, val: 2 } ],
newArray = array.map((o, i) => ({ ...o, key: i+1}));
console.log(newArray)
Because it looks like you want to perform side-effects rather than create a new array, use forEach instead of .map. You also need to actually increment the count variable on each iteration:
let count = 0;
const arr1=[{key:'a', val:1},{key:'b',val:2}]
arr1.forEach(el => {
count++;
el.key = count;
});
console.log(arr1)
Use ++ to update count while getting the new value. Also, you need to return the modified el from map, and make sure you assign the return value otherwise it'll be garbage-collected - map returns a new array.
let count = 0;
const arr1 = [{key:'a',val:1},{key:'b',val:2}];
const res = arr1.map(({ val }) => ({ key: ++count, val }));
console.log(res);

How to name Values in array by values in different array?

I have two arrays:
The first contains unique names of fields in a nested array:
[0][0]:Name1
[0][1]:Name2
[0][2]:Name3
etc.
The second contains multiple items with values in a nested array like this:
[0][0] XYZ
[0][1] XYZA
[0][2] XYZ2
[1][0] XYZaa
[1][1] XYZas
[1][2] XYA
etc
What I want to do is to merge it and name it in this way:
[0] Name1: XYZ
[0] Name2: XYZA
[0] Name3: XYZ2
[1] Name1: XYZaa
[1] Name2: XYZas
[1] Name3: XYA
To achieve this I first attempted the following:
var mergedArr = name.concat(data);
That works fine, however I believe I can also use lodash to get closer to what I want:
_.merge(name, data)
and should work fine too.
I was trying to name it by using
_.zipObject
Yet it doesn't work the way I would like
I was trying few options with zip, zipObject, yet non of it gave me expected output.
Edit1:
how I created arrays:
$("#T1020 tr").each(function(x, z){
name[x] = [];
$(this).children('th').each(function(xx, zz){
name[x][xx] = $(this).text();
});
})
$("#T1020 tr").each(function(i, v){
data[i] = [];
$(this).children('td').each(function(ii, vv){
data[i][ii] = $(this).text();
});
})
If I understand your question correctly, you're wanting to zip array1 and array2 into a single array where:
each item of the result array is an object
the keys of each object are values of array1[0], and
the values of each key corresponding nested array of array2
To produce the following:
[
{
"name1": "xyz",
"name2": "xyza",
"name3": "xyz2"
},
{
"name1": "xyzaa",
"name2": "xyzas",
"name3": "xya"
}
]
This can be achieved without lodash; first map each item of array2 by a function where array1[0] is reduced to an object. The reduced object is composed by a key that is the current reduce item, and a value that is taken from the indexed value of the current map item:
const array1 = [
['name1', 'name2', 'name3']
]
const array2 = [
['xyz', 'xyza', 'xyz2'],
['xyzaa', 'xyzas', 'xya']
]
const result = array2.map((item) => {
/* Reduce items of array1[0] to an object
that corresponds to current item of array2 */
return array1[0].reduce((obj, value, index) => {
return { ...obj,
[value]: item[index]
};
}, {});
});
console.log(JSON.stringify(result, null, ' '));
Iterate the values (your array2) and take the sub-array from the keys (array) using the current index and the % operator. This will ensure that if that the keys are taken in a cyclic way (see example with keys2 and values2). Convert to object with _.zipObject:
const fn = (keys, values) => values.map((v, i) => _.zipObject(keys[i % keys.length], v))
const keys1 = [['name1', 'name2', 'name3']]
const values1 = [['xyz', 'xyza', 'xyz2'], ['xyzaa', 'xyzas', 'xya']]
const keys2 = [['name1', 'name2', 'name3'], ['name11', 'name12', 'name13']]
const values2 = [['xyz', 'xyza', 'xyz2'], ['xyzaa', 'xyzas', 'xya'], ['abc', 'def', 'hij']]
console.log(fn(keys1, values1))
console.log(fn(keys2, values2))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

Categories

Resources