Convert an object with multiple values per key into array of objects in JS
const obj = { "a": [1, 2], "b": [3, 4], "c": [5, 6] }// create an array to store resultconst result = []// for each key in objObject.keys(obj).forEach(key => { // for each array element of the property obj[key] obj[key].forEach((value, index) => { // if an object doesn't exists at the current index in result // create it if (!result[index]) { result[index] = {} } // at the result index, set the key to the current value result[index][key] = value })})console.log(result)
Javascript multiple value object to simple array
You are getting error because of this line obj1[key].forEach((value, index)
, because it is an object
and you are trying to use forEach
on an object.
For example obj1[key]
will give the value of A
and B
etc keys which as an object like {bottom: 63, mid: 4, top: 15}
.
You can us only for..in
and then use destructing to push the values in the array
const obj1 = { A: { bottom: 63, mid: 4, top: 15 }, B: { bottom: 30, mid: 23, top: 5 }, C: { bottom: 41, mid: 25, top: 16 }}
const result = []
for (let key in obj1) { result.push(Object.assign({}, obj1[key], { group: key }))
}
console.log(result)
How to convert an object to array of multiple objects in javascript
const myObjects = {};
Object.keys(data).map((key) => {
const splitKey = key.split('-');
const elemId = splitKey[1];
const realKey = splitKey[0];
if (!myObjects[ elemId ]) {
myObjects[ elemId ] = { id: elemId }; // Create entry
}
myObjects[ elemId ][ realKey ] = data[ key ];
});
// Turn into array
const myObjectsToArray = Object.values(myObjects);
// Or use the myObjects as a key/value store with ID as index
const selectedElement = myObjects[ myID ];
Fill array of objects with multiple keys and values
You can simply use an array syntax :
Considering
let yourObject = {}
You can use [] to define a property
yourObject["color"] = "red"
So with your logic, you can do :
yourObject[key] = value
Tip :
Using int strings as index is not really a good pratice because JS reindexes arrays, i advise you to construct your object like this :
[
{
id: 3
color: "red",
sex: "male",
size: "40"
},
{
id: 5,
color: "black",
sex: "female",
size: "36"
},
{
id: 8,
color: "black",
sex: "female",
size: "36"
},
...
];
How to convert object key value pair with array as values to multi objects of key value pair?
You can do something like this
const obj = {
status: ["new", "old"],
place: ["york", "blah"]
};
const result = {};
Object.keys(obj).forEach((key, index) => {
result[`newObj${index + 1}`] = obj[key].map(item => ({[key]: item}));
});
console.log(result);
How to convert an Object {} to an Array [] of key-value pairs in JavaScript
You can use Object.keys()
and map()
to do this
var obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0}
var result = Object.keys(obj).map((key) => [Number(key), obj[key]]);
console.log(result);
How to store multiple values in to objects within an array
An example using index as unique for displaying purpose.
const data = {
items: [
{
id: 119603782,
node_id: "MDEwOlJlcG9zaXRvcnkxMTk2MDM3ODI=",
name: "react-contextual",
full_name: "drcmda/react-contextual",
private: false,
owner: {
login: "drcmda",
id: 2223602,
},
},
{
id: 119603782,
node_id: "MDEwOlJlcG9zaXRvcnkxMTk2MDM3ODI=",
name: "react-contextual",
full_name: "drcmda/react-contextual",
private: false,
owner: {
login: "drcmda",
id: 2223602,
},
},
],
};
const items = data.items.map((item, idx) => ({ ...item, idx }));
// new item
const newItem = {
id: 119603782,
node_id: "MDEwOlJlcG9zaXRvcnkxMTk2MDM3ODI=",
name: "react-contextual",
full_name: "drcmda/react-contextual",
private: false,
owner: {
login: "drcmda",
id: 2223602,
},
};
function addNewItems(items, newItem) {
newItem.idx = items.length;
items.push(newItem);
return items;
}
console.log(addNewItems(items, newItem));
Convert object with multiple arrays to array of objects
You could map the arrays with new objects.
const
objData = { arr1: [1, 2, 3], arr2: [1, 2, 3], arr3: [2, 1, 2], arr4: ["a", "b", "c"] },
keys = { arr1: 'a', arr2: 'b', arr3: 'c', arr4: 'd' },
result = Object
.entries(objData)
.reduce((r, [key, array]) => array.map((v, i) => ({ ...r[i], [keys[key]]: v })), []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
How to convert multiple Objects to an Array [] of key-value pairs in javascript
That's because you are telling it to change just the first (index 0) value in the array.
First of all, you need to use Object.values as said by matevzpoljianc, after that you need to loop trough all your array.
So it would be:
let table = this.state.payments;
const tableD = this.state.payments.map(item=>Object.values(item))
console.log(tableD);
Now you would've your array of arrays.
EDIT.
If you server is responding with an object that has numbers as keys then what I've wrote won't work, but you can simply hotfix it to:
let table = this.state.payments;
const tableD = Object.values(this.state.payments).map(item=>Object.values(item))
console.log(tableD);
Related Topics
Bootstrap Datepicker Appearing At Incorrect Location in a Modal
How to Convert Date Format from Dd.Mm.Yyyy to Dd/Mm/Yyyy in JavaScript
Copy/Paste from Excel to a Web Page
How to Validate for Only CSV File Uploads Using the Pattern Attribute Using Html5
Mongodb, Update Collection Field If New Value Is Not Null
Callback Function Cannot Access Variable Within Parent Function'S Scope
Hide Options in Select2 Multi Select
How to Add and Remove Class to Menu Items on Mouseover
Check Whether Elements from One Array Are Present in Another Array
How to Remove Row Borders in a Specific Column
Javascript: Get All Months Between Two Dates
Regex to Match Words With Hyphens And/Or Apostrophes
How to Check If Value Is in Array With Angularjs
Prevent Bootstrap Modal Window from Closing on Form Submission
Combining JavaScript and CSS into HTML File
How to Add Counter in Angular 6
Can Vue-Router Open a Link in a New Tab
Trigger Click in Typescript - Property 'Click' Does Not Exist on Type 'Element'