This question already has answers here:
Get array of object's keys
(8 answers)
Closed 2 years ago.
I have this following object:
{
12232: [],
34232: [],
23435: []
}
I want to extract the keys from this object to show them as labels in my React frontend. How can I accomplish this?
The method Object.keys() allows you to loop over the keys of an object.
You should be able to use it in order to get what you want.
See here
Use JS built-in Object.keys() for that.
const myObject = {
12232: [],
34232: [],
23435: []
};
const keys = Object.keys(myObject);
keys.forEach(key => {
console.log(key);
});
You can always use
obj = { abc: "1", def: "2" }
console.log(Object.keys(obj))
It will log ["abc", "def"]. Then you can map through this array and display the values as required.
Ref
You could use Object.keys to extract the keys out of your object.
You could check the docs of Object.keys here
const obj = {
12232 : [],
34232 : [],
23435: []
}
Object.keys(obj); // returns ['12232', '34232', '23435'];
Related
This question already has answers here:
Get all unique values in a JavaScript array (remove duplicates)
(91 answers)
Closed 1 year ago.
I have this array of objects, my aim is to remove dublicate values from values array, I want the result to be [{name:'test1', values:['35,5', '35,2','35,3']}, {name:'test2', values:['33,2', '34,3', '32,5']}]
I have tried following solution but it does not works, Do you have any suggestions? Thanks in advance
let arr = [{name:'test1', values:['35,5', '35,2', '35,2', '35,3', '35,5']},
{name:'test2', values:['35,1', '35,1', '33,2', '34,3', '32,5']}]
let uniqueArray = arr.values.filter(function(item, pos) {
return arr.values.indexOf(item.values) == pos;
})
console.log(uniqueArray)
}
}
You can easily remove duplicates from an Array by creating a new Set based off it.
Set objects are collections of values. You can iterate through the elements of a set in insertion order. A value in the Set may only occur once; it is unique in the Set's collection
If you want the result in an array, just use spread syntax for that, for example:
let arr = [{
name: 'test1',
values: ['35,5', '35,2', '35,2', '35,3', '35,5']
},
{
name: 'test2',
values: ['35,1', '35,1', '33,2', '34,3', '32,5']
}
];
const uniqueArr = arr.reduce((accum, el) => {
// Copy all the original object properties to a new object
const obj = {
...el
};
// Remove the duplicates from values by creating a Set structure
// and then spread that back into an empty array
obj.values = [...new Set(obj.values)];
accum.push(obj);
return accum;
}, []);
uniqueArr.forEach(el => console.dir(el));
This question already has answers here:
Return object with default values from array in Javascript
(4 answers)
How to convert an Object {} to an Array [] of key-value pairs in JavaScript
(21 answers)
Closed 4 years ago.
What's the best way to convert an array, to an object with those array values as keys, empty strings serve as the values of the new object.
['a','b','c']
to:
{
a: '',
b: '',
c: ''
}
try with Array#Reduce
const arr = ['a','b','c'];
const res = arr.reduce((acc,curr)=> (acc[curr]='',acc),{});
console.log(res)
You can use Array.prototype.reduce()and Computed property names
let arr = ['a','b','c'];
let obj = arr.reduce((ac,a) => ({...ac,[a]:''}),{});
console.log(obj);
const target = {}; ['a','b','c'].forEach(key => target[key] = "");
You can use Object.assign property to combine objects created with a map function, please take into account that if values of array elements are not unique the latter ones will overwrite previous ones
const array = Object.assign({},...["a","b","c"].map(key => ({[key]: ""})));
console.log(array);
You can use array reduce function & pass an empty object in the accumulator. In this accumulator add key which is denoted by curr
let k = ['a', 'b', 'c']
let obj = k.reduce(function(acc, curr) {
acc[curr] = '';
return acc;
}, {});
console.log(obj)
This question already has answers here:
Concatenate Object values
(4 answers)
Closed 7 months ago.
I'm looking at an efficient way to merge multiple array props in an object.
The object, can have multiple array properties in there :
{
"col0Codes": [
"ABC",
"XYZ",
"UYA",
"ZZA",
"AAW",
"MYP"
],
"col1Codes": [
"CNA",
"ZYA",
"OIA",
"POQ",
"LMO",
"OPI"
],
"col2Codes": [
"CNA",
"ZYA",
"OIA",
"POQ",
"LMO",
"OPI"
],
"col3Codes": [
"..."
],
"col4Codes": [
"..."
],
...
}
Result: All the codes in a single array
["ABC","XYZ","UYA","ZZA","AAW","MYP","CNA","ZYA","OIA","POQ","LMO","OPI",....]
I've tried using concat but this creates a new array every single time and overwrites the previous one, I feel this is not fast and memory efficient.
let colCodes = []
for (let i in data) {
colCodes = colCodes .concat(i)
}
console.log(activityCodes)
I've tried using push, but for some reason it does not merge all the entries into one single array but creates a single array with number of props in the object as shown below
let colCodes = []
for (let i in data) {
colCodes.push(i)
}
console.log(colCodes)
[Array(6), Array(5), ....]
Is there anyway I can achieve this using reduce, if that is what'll be fast and mem efficient ?
You can get an array of arrays using Object.values(), and then flatten them to a single array using Array.flat():
const data = {"col0Codes":["ABC","XYZ","UYA","ZZA","AAW","MYP"],"col1Codes":["CNA","ZYA","OIA","POQ","LMO","OPI"],"col2Codes":["CNA","ZYA","OIA","POQ","LMO","OPI"]};
const result = Object.values(data).flat();
console.log(result);
Old answer:
You can get the Object.values(), then merge by spreading into Array.concat():
const data = {"col0Codes":["ABC","XYZ","UYA","ZZA","AAW","MYP"],"col1Codes":["CNA","ZYA","OIA","POQ","LMO","OPI"],"col2Codes":["CNA","ZYA","OIA","POQ","LMO","OPI"]};
const result = [].concat(...Object.values(data));
console.log(result);
You could also simply Array.reduce the Object.values with ES6 spread:
const input={"col0Codes":["ABC","XYZ","UYA","ZZA","AAW","MYP"],"col1Codes":["CNA","ZYA","OIA","POQ","LMO","OPI"],"col2Codes":["CNA","ZYA","OIA","POQ","LMO","OPI"]};
console.log(Object.values(input).reduce((r,c) => [...r, ...c]))
One way would be to use Array.prototype.flat, and call it on the values of the object:
const input={"col0Codes":["ABC","XYZ","UYA","ZZA","AAW","MYP"],"col1Codes":["CNA","ZYA","OIA","POQ","LMO","OPI"],"col2Codes":["CNA","ZYA","OIA","POQ","LMO","OPI"]};
console.log(
Object.values(input).flat()
);
You can try this
let obj = {"col0Codes": ["ABC","XYZ","UYA","ZZA","AAW","MYP"],
"col1Codes": ["CNA","ZYA","OIA","POQ","LMO","OPI"],
"col2Codes": ["CNA","ZYA","OIA","POQ","LMO","OPI"],
"col3Codes": ["..."],
"col4Codes": ["..."]
}
let op = [];
for(let key in obj){
op.push(...obj[key])
}
console.log(op)
This question already has answers here:
Sort array of objects by string property value
(57 answers)
Closed 5 years ago.
Since there's no official way to sort an object by values, I'm guessing you either (1) Use an array instead or (2) Convert your object to an array using Object.entries(), sort it, then convert back to an object. But option (2) is technically unsafe since Javascript objects aren't supposed to have order.
Now I have a React app where I'm using Redux. I'm storing my data not as an array but as an object iterated by id values. This is what Redux suggests, and I would do it anyways, because of lookup times. I want to sort this redux data, so what I'm currently doing is option (2) of converting to array and then back to object. Which I don't really like.
My question is: Is this what everyone else does? Is it safe to sort an object?
Example:
const sortObject = (obj) => {
//return sorted object
}
var foo = {a: 234, b: 12, c: 130}
sortObject(foo) // {b: 12, c:130, a:234}
this is what I'm currently doing.
My object data structure looks something like this
obj = {
asjsd8jsadf: {
timestamp: 1234432832
},
nsduf8h3u29sjd: {
timestamp: 239084294
}
}
And this is how I'm sorting it
const sortObj = obj => {
const objArray = Object.entries(obj);
objArray.sort((a, b) => {
return a[1].timestamp < b[1].timestamp ? 1 : -1;
});
const objSorted = {};
objArray.forEach(key => {
objSorted[key[0]] = key[1];
});
return objSorted;
};
If you are using the Redux documentation for reference you should also have an array with all of the id's in it. Wouldn't it be easier to just sort that array and then use insertion sort when you add something to the state. Then you could use the sorted array to access the byId property of the state?
This question already has answers here:
Return object with default values from array in Javascript
(4 answers)
How to convert an Object {} to an Array [] of key-value pairs in JavaScript
(21 answers)
Closed 4 years ago.
What's the best way to convert an array, to an object with those array values as keys, empty strings serve as the values of the new object.
['a','b','c']
to:
{
a: '',
b: '',
c: ''
}
try with Array#Reduce
const arr = ['a','b','c'];
const res = arr.reduce((acc,curr)=> (acc[curr]='',acc),{});
console.log(res)
You can use Array.prototype.reduce()and Computed property names
let arr = ['a','b','c'];
let obj = arr.reduce((ac,a) => ({...ac,[a]:''}),{});
console.log(obj);
const target = {}; ['a','b','c'].forEach(key => target[key] = "");
You can use Object.assign property to combine objects created with a map function, please take into account that if values of array elements are not unique the latter ones will overwrite previous ones
const array = Object.assign({},...["a","b","c"].map(key => ({[key]: ""})));
console.log(array);
You can use array reduce function & pass an empty object in the accumulator. In this accumulator add key which is denoted by curr
let k = ['a', 'b', 'c']
let obj = k.reduce(function(acc, curr) {
acc[curr] = '';
return acc;
}, {});
console.log(obj)