Convert 2 arrays into key value object javascript - javascript

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
})
}

Related

Javascript: How to convert a Map to an Object that has an object as its keys?

let johnB = { name: "John Boy" },
lilyA = { name: "Lily Allen" },
peterD = { name: "Peter Drucker" };
const users = new Map([
[johnB, 'boudler'],
[lilyA, 'rock'],
[peterD, 'stone']
])
const obj = {};
users.forEach((value, key) => obj[key].name = value)
console.log(obj)
The above doesn't work but it shows the basic intent. I want to get name property from the map keys to be the key when the Map is "converted" to an object. Accessing just the key(without .name), javascript stringifies the object so you end up with [object, Object] as the key.
…an Object that has an object as its keys?
That does not exist. An object property cannot have an object as the key, it must be a string or a symbol. What are you attempting to achieve is simply not possible. Keep using the Map - that's what it is meant to be used for.
I think you just have your logic wrong in your foreach loop.. Is this what you were expecting?
{
"John Boy": "boudler",
"Lily Allen": "rock",
"Peter Drucker": "stone"
}
let johnB = { name: "John Boy" },
lilyA = { name: "Lily Allen" },
peterD = { name: "Peter Drucker" };
const users = new Map([
[johnB, 'boudler'],
[lilyA, 'rock'],
[peterD, 'stone']
])
const obj = {};
users.forEach((value, key) => obj[key.name] = value)
console.log(obj)

how to convert nested array of objects to object of array

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);

How to convert url array query to object in Javascript

I have an URL with query params like this:
myLocalSite/?attributes%5B0%5D%5Bname%5D=customer_property_number&attributes%5B0%5D%5Bop%5D=equal&attributes%5B0%5D%5Bvalue%5D=12&attributes%5B1%5D%5Bname%5D=feedback_tags&attributes%5B1%5D%5Bop%5D=in&attributes%5B1%5D%5Bvalue%5D=test+1%2Cwww
after JSON parsing it convert into next structure
{
attributes[0][name]: "customer_property_number"
attributes[0][op]: "equal"
attributes[0][value]: "12"
attributes[1][name]: "feedback_tags"
attributes[1][op]: "in"
attributes[1][value]: "test 1,www"
}
In the end, I need an array that look like this:
attributes = [
{
name: 'customer_property_number',
op: 'equal',
value: '12',
},
{
name: 'feedback_tags',
op: 'in',
value: 'test 1, www',
},
]
Now does anyone know how I can then put these items into attributes array?
Thanks!
Here is the approach using URLSearchParams and going over each search param, parse and push to array of objects.
var sp = new URLSearchParams(
"myLocalSite/?attributes%5B0%5D%5Bname%5D=customer_property_number&attributes%5B0%5D%5Bop%5D=equal&attributes%5B0%5D%5Bvalue%5D=12&attributes%5B1%5D%5Bname%5D=feedback_tags&attributes%5B1%5D%5Bop%5D=in&attributes%5B1%5D%5Bvalue%5D=test+1%2Cwww"
);
var attributes = [];
for (entry of sp) {
const [attr, value] = entry;
const [index, key] = attr
.split("[")
.filter(x => x.includes("]"))
.map(x => x.slice(0, -1));
if (!attributes[Number(index)]) {
attributes[Number(index)] = {};
}
attributes[Number(index)][key] = value;
}
console.log(attributes);

Convert single object into array of objects

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);

Return an Object Key and Value from an Array with lodash

I have this Array, I need to get out each name and age value, and then make the name value a new key and the age value a new value.
The Array
var arr = [
{name: "jack", age: 32 },
{name: "jane", age: 34 }
]
My previous code
var monthlyProfit = _.map(arr, function(v) {
var obj = {
v.name: v.age
};
return obj;
});
console.log(monthlyProfit) // Error
Expectation
var arr = [
{jack: 32},
{jane: 34}
]
I am using lodash, but vanilla JS won't be a problem.
The way you're currently trying to define the property will not work. There are multiple ways to achieve what you're trying to achieve, but I'd usually do it like this (using ES5):
var monthlyProfit = _.map(arr, function(v) {
return {[v.name] : v.age};
});
Or like this, as ES6 one-liners:
//using lodash
var monthlyProfit = _.map(arr, ({ name, age }) => ({ [name]: age }))
//or, pure ES6 without lodash:
var monthlyProfit = arr.map(({ name, age }) => ({ [name]: age }))
You should be seeing Syntax Error: Unexpected token . at the line where you're creating the object in your current code.

Categories