how to add key of object in array? - javascript

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)

Related

how convert values string into a integer object array by key

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

What is the best way to access key/values of a object array when I don't know them?

I have this array above and I need every property of it
let arr = [{'John': 0}, {'Doe': 50}, {'Marry': 100}]
How could I extract every single key/value of it, once in theory, I don't know any of them?
I have already tried using object.keys but it returns the indexes of my array.
This should work
const arr = [{'John': 0}, {'Doe': 50}, {'Marry': 100}];
// to iterate over each element in the arry
arr.forEach(a => {
// To Iterate over each key in the element object
Object.keys(a).forEach(k => {
// to print the value of the 'k' key
console.log(k + ' : ' + a[k]);
})
})
1) You can use flatMap and Object.keys to get keys from an array of objects.
let arr = [{ John: 0 }, { Doe: 50 }, { Marry: 100 }];
const result = arr.flatMap((o) => Object.keys(o));
console.log(result);
2) To find all values in an array
let arr = [{ John: 0 }, { Doe: 50 }, { Marry: 100 }];
const values = arr.flatMap((o) => Object.values(o));
console.log(values);
3) If you want to find out all keys and values in an object
let arr = [{ John: 0 }, { Doe: 50 }, { Marry: 100 }];
const result = {
keys: [],
values: [],
};
for (let obj of arr) {
Object.entries(obj).map(([k, v]) => {
result.keys.push(k);
result.values.push(v);
});
}
console.log(result);
If you want to collect all the keys and values of a nested array of objects, you can use Array.prototype.reduce and then collect the keys and values of the nested objects in separate nested arrays, using Object.keys() and Object.values() respectively:
const arr = [{'John': 0}, {'Doe': 50}, {'Marry': 100}];
const allKeysAndValues = arr.reduce((acc, cur) => {
acc.keys.push(...Object.keys(cur));
acc.values.push(...Object.values(cur));
return acc;
}, { keys: [], values: [] });
console.log(allKeysAndValues);
A one liner could be
let arr = [{'John': 0}, {'Doe': 50}, {'Marry': 100}]
console.log( arr.map( obj => Object.entries(obj)));

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;
}

Convert String into Array in Javascript Angular 6

I have a dynamically generated Array that is shown from console.log(temp):
[{user_id: "test#random.com", status: "Idle"}],
[{user_id: "whatever#random.com", status: "Busy"}]
My code:
this.scheduleService.getShiftSchedule().subscribe((temp)=>{
this.api = temp;
console.log(temp);
})
How do I change the format of my Array to become like the Array below?
[[{id: 1,content: 'test#random.com'},{id: 2,content: 'Idle'}],
[{id: 1,content: 'whatever#random.com'},{id: 2,content: 'Busy'}]]
You could map the objects by taking an array of the wanted keys and their id.
var data = [{ user_id: "test#random.com", status: "Idle" }, { user_id: "whatever#random.com", status: "Busy" }],
ids = [['user_id', 1], ['status', 2]],
result = data.map(o => ids.map(([key, id]) => ({ id, content: o[key] })));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
var array = JSON.parse("[" + string + "]");
var arr = [1,2,3,4,5,6,7,8,9]
var newArr = [];
while(arr.length) newArr.push(arr.splice(0,3));
console.log(newArr)
you may try like this

Reduce JavaScript Objects into Array of Formatted Objects

I have an array of objects in the format
{type: number, sub_type: number}
I need to sort them into an array of objects formatted like this
{
type_id: (type from at least one object in array above),
sub_types: [
(all sub types from objects in array above that match this type)
]
}
This is what I came up but I think there is a more efficient way. rawTypes is an array of objects in need of formatting, types ends up being the array of formatted objects.
const typeIds = [...new Set(rawTypes.map(val => val.type))];
const types = typeIds.map(val => ({type_id: val, sub_types: [] }));
rawTypes.forEach(obj => {
let typeIndex = types.reduce((accum, val, i) => val.type_id === obj.type ? i : accum, 0);
types[typeIndex].sub_types.push(obj.sub_type);
});
I think a better solution would use recursion but I can't think of how to do it.
Look at this approach
var data = [{type: 5, sub_type: 10}, {type: 5, sub_type: 11}, {type: 6, sub_type: 12}];
var obj = data.reduce((a, c) => {
var current = a[`type_id_${c.type}`];
if (current) {
current.sub_types.push(c.sub_type);
} else {
var key = `type_id_${c.type}`;
a = { ...a, ...{ [key]: {sub_types: [c.sub_type], 'key': c.type} } };
}
return a;
}, {});
var array = Object.keys(obj).map((k) => ({ 'type': obj[k].key, 'subtypes': obj[k].sub_types }));
console.log(array)
.as-console-wrapper {
max-height: 100% !important
}

Categories

Resources