I have the following object
"data":{
"name 1":"a",
"name 2":"b",
"name 3":"b",
},
How can I convert to array of objects that will keep both the name and data "a", "b" so I can map and render compoents for each one passing in the both the name and data?
If you use a reduce function you can do the following to achieve your goal
Object.keys(data).reduce((array, key) => {
return [...array, {key: data[key]}]
}, [])
Reduce is a cool function that iterates and combine data into one single item (could be 1 object, array, integer, etc).
Object.keys() is a way to get each key from the current object and be able to iterate over each.
The solution provided by Tall Paul will work perfectly but you can also use Object.entries(). It states that
The Object.entries() method returns an array of a given object's own enumerable property [key, value] pairs, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).
so you can try something like this
let result = Object.entries(data);
result.map((item, index)=>{
console.log('key is:- ', item[0], ' and value is:- ', item[1]);
});
you can get all the keys in the object in an array using Object.keys function and use map function to get the desired output.
This will convert to array of objects that will keep both the name and data.
var data = {
"name 1":"a",
"name 2":"b",
"name 3":"b",
}
var res = Object.keys(data).map(function(name){
var obj = {};
obj[name] = data[name];
return obj;
});
console.log(res);
js native method u can use;
var data = {
"name 1":"a",
"name 2":"b",
"name 3":"b",
};
var newObj = [...Object.values(data), ...Object.keys(data)]
console.log(newObj)
Related
This question already has answers here:
How do I loop through or enumerate a JavaScript object?
(48 answers)
Closed 1 year ago.
I have object like this:
{
"first" : "value1",
"second" : "value2"
}
I want to access both values in for cycle. Order of getting values doesn't mind. Usage is for something like value = value + "something". How to acces values which key names I don't know? Of course I can get keys from helping array like:
var keys = ["first", "second"];
And then get them by index and with them get value1 and value2 from my original array. Is there some better way? For some reason foreach doesn't work either.
Javascript has a for ... in to loop through keys
for (var key in object) {
console.log(object[key])
}
To access both values:
const data = {
"first": "value1",
"second": "value2"
};
// (1) for-loop
for (const [key, value] of Object.entries(data)) {
console.log("for-loop:", key, value);
}
// (2) Array.prototype.forEach
Object.entries(data).forEach(([key, value]) => {
console.log("Array.prototype.forEach:", key, value);
});
If you just want the keys and values separately in an array you can do the following:
var data = {
"first" : "value1",
"second" : "value2"
}
var keys = Object.keys(data)
var values = Object.values(values)
Printing them out individually would give you:
console.log(keys)
Output: ["first", "second"]
console.log(values)
Output: ["value1", "value2"]
I want to iterate through my key/value pairs and push all the values for each key into its own array. These arrays of values of each key should be pushed to a single output array.
I hope this explains what I'm trying to do:
Input: map = {"hi":["hello","hey","howdy"],"bye":["Goodbye","Ciao"]}
Output: output = [["hello","hey","howdy"],["Goodbye","Ciao"]]
This is what I have so far:
return Object.keys(map).reduce((output, key) => {
return output.push(map[key])
},[])
Any help on iterating through the values for each key and adding those values to an array within another output array would be greatly appreciated.
For background, this is part of a grouping anagrams problem so I'm populating my Map as follows from a provided array "str" of strings.
let map = {};
str.forEach(anagram => {
const sortedWord = anagram
.split("")
.sort()
.join("");
map[sortedWord] = map[sortedWord] || [];
map[sortedWord].push(anagram);
});
All you need is the built-in Object.values():
Object.values() returns an array whose elements are the enumerable property values found on the object.
const map = {"hi":["hello","hey","howdy"],"bye":["Goodbye","Ciao"]};
const output = Object.values(map);
console.log(output);
Using reduce the return pushs to 'output' no need to push yourself:
return Object.keys(map).reduce((output, key) => {
return map[key]
},[])
You could also use map:
return Object.keys(map).map((key) => {
return map[key]
})
Apart from the above two excellent answers, you may choose to use Object.entries(), which will return an array from the input object's [key, value] pair. From there, we can return only the value into the resulting array, giving you the expected result.
const input = {"hi":["hello","hey","howdy"],"bye":["Goodbye","Ciao"]}
const result = Object.entries(input).map(item => item[1]);
console.log(result);
However, do take note that Object.entries() is not supported by Internet Explorer browsers.
Alternatively, you may use the good old for..in statement to iterate through the enumerable properties of the object, followed by pushing the corresponding values to the resulting array.
const input = {"hi":["hello","hey","howdy"],"bye":["Goodbye","Ciao"]}
const result = []
for (const property in input) {
result.push(input[property]);
}
console.log(result);
I am fairly new to JavaScript and I am trying to extract the name Sam from the array. The output that I'm getting is name. How do I get Sam? Thank you in advance. I apologize but I know this is a fairly novice question.
I am trying to loop by using forEach.
let Person = {
name: ['Sam']
}
let handler = Object.keys(Person)
handler.forEach(function(element){
console.log(element)
})
Object.keys() only gives you keys
Use Object.entries() if you want key and value
Use Object.values() if you only want values
let Person = {
name: ['Sam']
}
for (const fn of ["values", "keys", "entries"]) {
console.log(`Using: Object.${fn}()`);
for (const v of Object[fn](Person)) {
console.log(v);
}
}
Instead of Object.keys use Object.values
If you know in advance that your name array is located under the key name, then access it directly
const person = { name: ['Sam'] };
console.log(person.name);
console.log(person.name[0]);
Otherwise, use Object.values() to enumerate the values in the object, but you might get more values than simply the names array and you will have to find out which value contains the names you are looking for:
const person = { name: ['Sam'], anotherProp: 'hello' };
console.log(Object.values(person));
Using Object.entries() is not helpful in this situation as if you use it, it means that you know under which property is located your name array, and if this is the case, simply access the array directly.
let Person = {
name: ['Sam',"Bob","Alice"]
}
let count = Person.name.length;
for(let i = 0; i<count; i++){
console.log( Person.name[i])
}
If you use Object.keys() you can get the value by using object[key] bracket notation or object.key dot notation.
Object.keys(obj).forEach(key => obj[key]);
let Person = {
name: ['Sam']
}
Object.keys(Person).forEach(name => console.log(`${name} = ${Person[name]}`));
What I am trying to accomplish is from an array, I want to map all of those values into one object. For example, if I have the following data below
const myKeys = ["prop_1", "prop_2", "prop_3"];
When I map over this array I would like to return an object with 3 properties from the array listed above. Something like this.
const myKeysObj = myKeys.map( key => {
// expected outcome {"prop_1" : "some_value", "prop_2": "some_value", "prop_3": "some_value"}
// actual outcome {key: "some_value"}
return {[key]: "some_value"}
})
What can I do to have all three of my props in my array to be properties for a each object returned?
It looks like you want to reduce the keys into an object, in which case reduce is more appropriate than .map:
const myKeys = ["prop_1", "prop_2", "prop_3"];
const output = myKeys.reduce((a, key) => {
a[key] = 'some_value';
return a;
}, {});
console.log(output);
I'm trying to convert a data structure like this:
data = {
0:{A:a},
1:{B:b},
2:{C:c},
}
into a structure like this:
[
{0:{A:a}},
{1:{B:b}},
{2:{C:c}},
]
Using the spread operator like this: [...data] returns any empty array.
I also tried [{...data}]
Is there a way to use the spread operator to get the desired result? Also, why doesn't this approach work?
"Is there a way to use the spread operator to get the desired result?" Short answer, no. (see below for alternate solution to what you're trying to accomplish)
"Also, why doesn't this approach work?"
It doesn't work because according to the MDN docs
"The Rest/Spread Properties for ECMAScript proposal (stage 3) adds spread properties to object literals. It copies own enumerable properties from a provided object onto a new object."
Like the docs say, according to the "Rest/Spread Properties proposal", you can't spread object properties onto an array, objects will always spread their properties onto a new object. Likewise, arrays will not spread onto an object, they will only spread onto a new array.
Alternative solution:
You can do this fairly easily with Object.keys().map(). Object.keys() will get an array of the keys of the object, and Array.map() will map them into an array of the desired structure, like so:
var data = {
0:{A:"a"},
1:{B:"b"},
2:{C:"c"},
}
var result = Object.keys(data).map(function (key) {
return { [key]: data[key] };
});
console.log(result);
You can use Object.entries to get [key, value] pairs, and map them to an array of objects using computed property names:
const data = {
0:{A: 'a'},
1:{B: 'b'},
2:{C: 'c'}
};
const result = Object.entries(data).map(([key, value]) => ({ [key]: value }));
console.log(result);
I'm afraid you cant use to spread operator like in your example, however you can produce the desired output with reduce.
data = {
0:{A:'a'},
1:{B:'b'},
2:{C:'c'},
}
let resArr = Object.keys(data).reduce((arr, e) => {
arr.push({[e]: data[e]});
return arr;
}, []);
console.log(resArr);
let data = ['Uzbek sila', 'Hikmatbet', 'Aslamboi']
let spread = [...data]
console.log(spread)