map function for objects (instead of arrays)
There is no native map
to the Object
object, but how about this:
var myObject = { 'a': 1, 'b': 2, 'c': 3 };
Object.keys(myObject).forEach(function(key, index) {
myObject[key] *= 2;
});
console.log(myObject);
// => { 'a': 2, 'b': 4, 'c': 6 }
.map() function is returning an array of arrays instead of array of objects
The solution may be one possible solution to achieve the below described output structure / format:
id: nested0.id, // outer-array "Id" prop
name: nested0.serve, // outer-array "serve" prop
date: nested1.name // inner-array "name" prop
Code Snippet
// method to obtain the array of transformed objects
const transformData = arr => (
arr.flatMap( // iterate the outer-array using "flatMap()"
({ Id, serve, childNested }) => ( // de-structure to directly access props
childNested.map( // iterate over inner-array "childNested"
({ name }) => ({ // de-structure to directly access "name" prop
id: Id, // structure the desired output object
name: serve,
date: name
})
)
)
) // implicit "return" will send the result of "flatMap()"
);
const rawData = [{
"Id": "tryuk34io98i",
"src": "planet",
"gwt": {
"gwtId": 918,
"name": "Request"
},
"serve": "Transit1",
"childNested": [{
"name": "xxl",
"version": "001",
"description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
"solved": {
"id": "tik",
"name": "face",
"isOn": "false"
},
"externalRef": [{
"type": "eight",
"uri": "git"
},
{
"type": "two",
"uri": "git"
}
],
"project": {
"name": "InProgress",
"version": "1",
"active": true
},
"used": 0,
"internal": false
}],
"affe": 0
},
{
"Id": "987ytrdfghv",
"src": "Space",
"gwt": {
"gwt": 918,
"name": "Request"
},
"serve": "Transit",
"childNested": [{
"name": "xxs",
"version": "02",
"description": "Nullam sed lorem nec sem lobortis porta. Morbi vitae lorem velit.",
"solved": {
"id": "tok",
"name": "back face",
"isOn": true
},
"externalRef": [{
"type": "one",
"uri": "http"
},
{
"type": "two",
"uri": "http"
}
],
"project": {
"name": "Fail",
"version": "1.1",
"active": false
},
"used": 0,
"internal": false
}],
"affe": 0
}
];
console.log(transformData(rawData));
Return one object insted of array of objects using map function [codesandbox]
Using forEach without changing the key names in the original object
var result = [];
Object.keys(options).forEach((element) => {
const item = Object.fromEntries(
Object.entries(options[element]).map(([k, v]) => {
k = k.replace(/_*\d+/g, "");
return [k, v]
})
)
result = [...result,{ id: element, ...item }]
// Or you could use push which is slightly faster
// To see benchmarks Google Spread operator vs push site: measurethat.net
// result.push({ id: element, ...options[element] });
});
document.getElementById("app").innerHTML = `<pre>${JSON.stringify(
result,
null,
4
)}</pre>`;
console.log(result);
The output
[
{
"id": "694",
"title": "Tiger",
"category": "848",
"description": "long description"
},
{
"id": "695",
"title": "Turtles",
"category": "347",
"description": "long description"
}
]
map function for objects (instead of arrays)
There is no native map
to the Object
object, but how about this:
var myObject = { 'a': 1, 'b': 2, 'c': 3 };
Object.keys(myObject).forEach(function(key, index) {
myObject[key] *= 2;
});
console.log(myObject);
// => { 'a': 2, 'b': 4, 'c': 6 }
How can use my object like a array using with map function
You want the Object.keys()
function or the Object.values
const SUB_THEME = {
blue: 'Blue',
yellow: 'Yellow',
pink: 'Pink',
purple: 'Purple',
orange: 'Orange',
green: 'Green'
}
//this returns the keys
const theme_keys = Object.keys(SUB_THEME)
//this returns the values
const theme_values = Object.values(SUB_THEME)
Then you can map them like
theme_keys.map( key => {/*code here*/})
theme_values.map( key => {/*code here*/})
Remove duplicates within the map function
you can achieve this using flatMap
to get all name objects and then map
to extract the name
field. After that a Set
to dedupe. [...new Set(..)]
converts the Set back to an array
const results = [{
"data": {
"labels": {
"results": [{
"name": "tom"
}, {
"name": "another name"
}]
}
}
}, {
"data": {
"labels": {
"results": [{
"name": "jerry"
}]
}
}
}, {
"data": {
"labels": {
"results": [{
"name": "tom"
}]
}
}
}]
const res = [...new Set(results.flatMap(({data:{labels: {results}}}) => results).map(({name}) => name))]
//alternative
//const res = [...new Set(results.map(({data:{labels: {results}}}) => results).flat().map(({name}) => name))]
console.log(res)
How to map `Object.values()` over an array of objects nesting objects?
Using Ramda, you have to use use R.map
twice:
- To map over the items in the array.
- To map over each value of the object.
const countries = [
{
"austria": { value: 1},
"canada": {value: 2},
"nepal": { value: 3},
"india": { value: 4}
},
{
"australia": { value: 10},
"france": { value: 20},
"egypt": { value: 40},
"usa": { value: 20}
},
{
"mexico": { value: 3},
"germany": { value: 100},
"southAfrica": { value: 1},
"china": { value: 10}
}
]
const result = R.map(R.map(Object.values))(countries);
console.log(result);
.as-console-wrapper { max-height: 100% !important }
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.28.0/ramda.min.js"></script>
How can I map through several arrays of objects using JSX in React?
Thanks to @John for the assist.
I overcomplicated my design. My JSON file contained arrays and objects, making it awkward to navigate.
After restructuring it to contain only arrays, it was a lot easier.
Also, as for the actual problem, I was shown that I needed to add another map function inside my original one to make it spit the data out the right way.
//...
Object.values(thing).map((innerThing, innerIndex) => (
<>
{console.log("\nouter/inner: "+outerIndex +", " +innerIndex)}
{console.log("\nData: \n\t"+innerThing[2] +"\n\t" +innerThing[8] + "\n\t" +innerThing[3]+"\n\t" + innerThing[4]+"\n\t"+innerThing[5])}
<TableRow key = {thing[0].toString()}>
<SuperTD>{innerThing[2]}</SuperTD>
<SuperTD>{innerThing[8]}lbs</SuperTD>
<SuperTD>{innerThing[3]}gp</SuperTD>
<SuperTD>{innerThing[4]}gp</SuperTD>
<SuperTD>{innerThing[5]}gp</SuperTD>
</TableRow>
</>
//...
Now, with the mapping sorted, this is the result:
Related Topics
What Does 'Return' Keyword Mean Inside 'Foreach' Function
Why Does Parseint Yield Nan With Array#Map
How to Retrieve Get Parameters from JavaScript
Question Mark and Colon in JavaScript
Choosing and Activating the Right Controls on an Ajax-Driven Site
How to Check For "Undefined" in JavaScript
JavaScript: Client-Side Vs. Server-Side Validation
Chrome/Firefox Console.Log Always Appends a Line Saying 'Undefined'
Explain the Encapsulated Anonymous Function Syntax
JavaScript Get Clipboard Data on Paste Event (Cross Browser)
Asp.Net MVC Jsonresult Date Format
Firebase Query If Child of Child Contains a Value
Use Dynamic Variable Names in JavaScript