I have an object that looks like:
var data = {first: '12/1/2019', second: '12/15/2019'}
I am trying to get into an array of objects using its keys and values like so:
var array = [
{phase: 'first', date: '12/1/2019'},
{phase: 'second', date: '12/15/2019'}
]
I have tried various things, but the closest I have gotten is using something like:
var array = Object.entries(data).map(([key, value]) => ({key,value}));
This gives me an array of objects like:
[
{key: 'first', value: '12/1/2019'},
{key: 'second', value: '12/15/2019'}
]
I'm close! but i can't figure out how to change key and value to be phase and date. Can someone please help me out?
You can actually just rename your key and value parameter names:
var array = Object.entries(data).map(([phrase, date]) => ({phrase,date}));
Try adding labels in object.
var data = {
first: '12/1/2019',
second: '12/15/2019'
}
var array = Object.entries(data).map(([key, value]) => ({
phase: key,
date: value
}))
console.log(array)
You are almost there try by adding the key to return object
var data = {
first: '12/1/2019',
second: '12/15/2019'
}
var array = Object.entries(data).map(([key, value]) => ({
phase: key,
date: value
}));
console.log(array)
Try the following solution using for...in to iterates over all non-Symbol, enumerable properties of an object.
const data = { first: '12/1/2019', second: '12/15/2019' };
const dataset = [];
for (const key in data) {
if (data.hasOwnProperty(key)) {
const element = data[key];
dataset.push({
phase: key,
date: element
});
}
}
console.log(dataset);
You can use map() on Object.keys()
var data = {first: '12/1/2019', second: '12/15/2019'}
let arr = Object.keys(data).map(x => ({phase:x,date:data[x]}))
console.log(arr)
You can also use Object.entries() and map() but give different names to the parameters destructed
var data = {first: '12/1/2019', second: '12/15/2019'}
let arr = Object.entries(data).map(([phase,date]) =>({phase,date}))
console.log(arr)
First extract the key (phase) and value (date) from the data object by Object.entries then use Array.reduce to accumulate and form the new object into an array.
const data = {first: '12/1/2019', second: '12/15/2019'}
const arr = Object.entries(data).reduce((acc, [phase, date]) => acc.concat({phase, date}), []);
console.log(arr);
Related
Hello I'm trying to create an object that includes under the same property name a bunch of array values,
This what I'm trying
const quiz = [
{question: 'Who is the main character of DBZ',
options: ['Vegetta','Gohan','Goku']}
]
const newObj = {
options: []
}
quiz.forEach((item)=>{
item.options.forEach((item, index)=>{
newObj.options[`name${index}`] = item
})
})
expected value =
newObj = {
options: [{name: 'Vegetta'},{name:'Gohan'},{name:'Goku'}]
}
actual value received =
newObj = {
{ options: [ name0: 'Vegetta', name1: 'Gohan', name2: 'Goku' ] }}
Thanks in advance!
As you've noticed, newObj.options[`name${index}`] = item creates a new key on your options array, and sets that to item. You instead want to push an object of the form {name: item} into your array. There are a few ways you could go about this, one way is to use .push() like so:
quiz.forEach((item)=>{
item.options.forEach((item)=>{
newObj.options.push({name: item});
})
});
while not as common, you can also use set the current index of options, which is slightly different to the above example, as it will maintain the same index, which can be important if quiz is a sparse array that you want to keep the same indexing of on options:
quiz.forEach((item)=>{
item.options.forEach((item, index)=>{
newObj.options[index] = {name: item};
})
});
Example of the difference:
const arr = [1, 2,,,5]; // sparse array
const pushRes = [];
const indxRes = [];
arr.forEach(n => pushRes.push(n));
arr.forEach((n, i) => indxRes[i] = n);
console.log("Push result", pushRes);
console.log("Index result", indxRes);
For a different approach, you also have the option of using something like .flatMap() and .map() to create your options array, which you can use to create newObj:
const quiz = [
{question: 'Who is the main character of DBZ',
options: ['Vegetta','Gohan','Goku']}
];
const options = quiz.flatMap(({options}) => options.map(name => ({name})));
const newObj = {options};
console.log(newObj);
Hello so i have array of objects something like this
const old = [{id: 1, name: 'Random'}, {id: 2, name: 'Random2'}]
also i have array
const wantedField = ['id']
So looking this result, i need values only for certain key
const finally = [[1],[2]]
I have tried something like this but not luck. End result should be array of arrays with just certain values.
old.map((obj, value) => {
const key = Object.keys(obj)[value]
if(wantedField.includes(const)) {
const newArray = []
const key = Object.keys(obj)[value]
newArray.push(obj[key])
return [newArray]
}
})
So this return [newArray] is wrong should return multiple values not just one. Please help regards.
This is a one-liner, with two nested maps. One to iterate over the input array, and another to iterate over the wanted field(s):
const old = [{id: 1, name: 'Random'}, {id: 2, name: 'Random2'}];
const wantedField = ['id'];
const result = old.map(o => wantedField.map(k => o[k]));
console.log(result);
I have an array with headers - say ["language", "name", "code"]
and an array of arrays of values - for example
[["English", "Matt", "2D"], ["Croatian", "Dana", "8S"], ["Russian", "Ivan", "2W"]].
I am trying to obtain an array of objects, like so:
[
{language: English, name: Matt, code: 2D},
{language: Croatian, name: Dana, code: 8S},
{language: Russian, name: Ivan, code: 2W}
]
Any elegant way to do this without nested for loops?
let props=["language", "name", "code"];
let data=[["English", "Matt", "2D"], ["Croatian", "Dana", "8S"], ["Russian", "Ivan", "2W"]];
let result=data.map( (innerArray) =>{let obj={};innerArray.forEach( (innerData,index) =>{obj[props[index]]=innerData;});return obj;
});
console.log(result);
const props = ["language", "name", "code"];
const values = [["English", "Matt", "2D"], ["Croatian", "Dana", "8S"], ["Russian", "Ivan", "2W"]];
const formatted = values.map(value => ({
[props[0]]: value[0],
[props[1]]: value[1],
[props[2]]: value[2],
}));
Or like this:
const formatted4 = values.map(value => {
let v = {};
props.forEach((prop, i) => {
v = {
...v,
[prop]: value[i]
}
});
return v;
});
You can create this without complexity, if the data count is constant, using ES6*
var dataList = [["English", "Matt", "2D"], ["Croatian", "Dana", "8S"], ["Russian", "Ivan", "2W"]];
let myList = [];
for([language, name, code] of dataList)
myList.push({language, name, code});
console.log(myList);
You can use array destructuring (assuming you're sure your data format stays the same) :
const newArr = [];
for(const [language, name, code] of yourDataArray){
//do whatever you want with the variables language, name, code
newArr.push({
language: language,
name: name,
code: code
})
}
I have got array of nested array of objects .
const data = [ {group: [{label:"1"}]}, {topGroup: [{label:"2"}]} ]
I want to convert array to this format of objects and I want to get this output
let permission ={
group:["1"],
topGroup:["2"]
}
How can I do this ?
const data = [ {group: [{label:"1"}]}, {topGroup: [{label:"2"}]} ]
const converted = data.reduce((a,b) => {
const onlyKey = Object.keys(b)[0];
a[onlyKey] = b[onlyKey].map(i => i.label);
return a;
}, {})
console.log(converted)
const data = [ {group: [{label:"1"}]}, {topGroup: [{label:"2"}]} ]
let permission = {};
data.forEach(val =>{
for(prop in val){
permission[prop] = [val[prop][0]["label"]]
}
})
console.log(permission)
Give this a upvote if this is what you want.
Assuming the data is going to have labels as in that format forever, you could use something like that
const data = [{"group":[{"label":"1"}]},{"topGroup":[{"label":"12"}]}];
// The dict variable under here is the second parameter of reduce that I passed it `{}`.
// The ind variable is the data at the index of the array.
var newData = data.reduce(function(dict, ind){
// You basically get the keys and the values and put them in place
// and return the last state to the reduce function.
dict[Object.keys(ind)] = Object.values(ind)[0][0]["label"];
return dict;
}, {})
console.log(newData)
Use destructuring and Object.fromEntries.
const data = [{ group: [{ label: "1" }] }, { topGroup: [{ label: "2" }] }];
const permission = Object.fromEntries(
data.map(item => {
const [[key, [obj]]] = Object.entries(item);
return [key, Object.values(obj)];
})
);
console.log(permission);
I would like to know how would I merge this bidimensional array
let arr[
['Reference', 'Price'],
['232323DD, 15.00]
];
I want to convert this into
[
{name: 'Reference', value: '232323DD'},
{name: 'Price', value: 15.00}
]
I've tried this:
Convert a two dimensional array into an array of objects
but It didn't work for me.
You can use .map():
let [keys, values] = [
['Reference', 'Price'],
['232323DD', 15.00]
];
let result = keys.map((k, i) => ({name: k, value: values[i]}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can map through the first array in that array and use their values as the keys to an object:
let arr = [
['Reference', 'Price'],
['232323DD', '15.00']
];
console.log(
arr[0].map((name, i) => ({name, value:arr[1][i]}))
)
If you are unsure about the size of the two arrays, you should first check whether their lengths are equal, to avoid undefined.
Other solution if you are not familiar with map (I think using map for this example make it a bit hard to read)...
const arr = [
['Reference', 'Price'],
['232323DD', 15.00]
]
const obj = []
arr.forEach(x => obj.push({name: x[0], value: x[1]}))
console.log(obj)
You can use the map function. It will run the callback on each array item, return it in a new array.
// where 'arr' is your original array
const new_arr = arr.map((item) => {
// this is called a 'destructuring assignment'
const [name, value] = item;
// return the values as fields in an object
return {name, value};
});
const arrArr = [['Reference', 'Price'], ['232323DD, 15.00]];
const objArr = [];
for (const item of arrArr) {
objArr.push({name: item[0], value: item[1]});
}
let arr = [
['Reference', 'Price'],
['232323DD', '15.00']
];
let result = arr[0].map((key, i) => ({name: key, value: arr[1] ? arr[1][i] : null}));
console.log(result);
I'll try to break this down:
// 1. create a new arr object:
let convertedArr = [];
// 2. loop over the original array:
for(let i = 0; i < arr.length; i++){
let currentItem = arr[i];
//create a temp object
let obj = {name:currentItem[0], value: name:currentItem[1] };
//push a new object to the array
convertedArr.push(obj);
}