convert nested array to nested obj in js - javascript

I am trying to convert the nested array to nested obj:
For ex,
let ip_array = [
["fdsfasdf","hghfhgh"],
["fsdf","hjghhjhj"],
["fdfss","hjghh"]
]
expected o/p :
let new_array = [
{"fsdfdsf":""fgdfgdfg},
{"dfdsd":"jhjghj"},
{"dfsddfds":"hghfh"}
]

This can be done with JavaScript's Array.map().
First, you use Array.map() to iterate through the input array, and return the result by using computed property names to set the key/property of each object.
const arr = [["fdsfasdf","hghfhgh"],["fsdf","hjghhjhj"],["fdfss","hjghh"]];
const res = arr.map(element => {
return {
[element[0]]: element[1]
};
});
console.log(res);

You could try
let ip_array = [["fdsfasdf","hghfhgh"],["fsdf","hjghhjhj"],["fdfss","hjghh"]]
let myObj = ip_array.map((a, k) => {
return { [a[0]]: a[1] };
})

An alternative approach using the newer Object.fromEntries() method.
Caution: This is very new method and is still in draft specification at the time of writing this answer in 2019. It may not be cross-browser compatible.
let ip_array = [
["fdsfasdf","hghfhgh"],
["fsdf","hjghhjhj"],
["fdfss","hjghh"]
]
let new_array = ip_array.map((arr)=> Object.fromEntries([arr]));
console.log(new_array);

Related

How i can to convert array to object of array in react?

I have a data in array
["Avengers","Batman","Spiderman","IronMan"]
how I can to covert to below
{"Avenger":"Avenger","Batmane":"Batman","Spiderman":"Spiderman","Ironman":"Ironman"}
You can do it like this:
let arr = ["Avengers","Batman","Spiderman","IronMan"];
let obj = arr.reduce((acc, item)=> ({...acc, [item]: item}) , {});
console.log(obj);
Someone else mentioned reduce, but I recommend against, copying objects at every iteration.
Here's a more performant approach.
const arr = ["Avengers","Batman","Spiderman","IronMan"];
const obj = {};
for (const el of arr) {
obj[el] = el;
}
console.log(obj);
You can use reduce to convert array to object.
You can see some examples in here Convert Array to Object

Convert string array into object with same key/value

How do I convert ["one","two","three"] into {one:"one", two:"two", three:"three"}
import stringArray from './a.js';
class b {
hashmap = stringArray// convert this into Object here inline.
}
Before you jump I know of for how to achieve this in say constructor() with tricks like forEach, for in loop etc. Is there a simple one line code to achieve this in the class property not inside a function.
Lodash
You can use _.zipObject. It accepts two arrays - one for keys, another for values but if you just use the same array twice you'd get matching pairs:
const arr = ["one","two","three"];
const obj = _.zipObject(arr, arr);
console.log(obj);
<script src="https://cdn.jsdelivr.net/npm/lodash#4.17.15/lodash.min.js"></script>
Plain JavaScript
You can use Object.fromEntries to do the same thing. It works with an array of key-value pairs, so you'll have to transform yours to that:
const arr = ["one","two","three"];
const matchingKeyValuePairs = arr.map(x => [x, x]);
const obj = Object.fromEntries(matchingKeyValuePairs);
console.log(obj);
Also you can use Array#reduce to generate an object with a computed property name:
const arr = ["one","two","three"];
const obj = arr.reduce((acc, item) => ({...acc, [item]: item}), {});
console.log(obj);
data = ["one","two","three"];
data = data.map(e => [e,e]) // keyvalue pairs [["one","one"],["two","two"],["three","three"]]
data = Object.fromEntries(data); // {"one":"one","two":"two","three":"three"}
map will convert each element of your input array to a structure you want.
In this case, we want to convert each element to an array with the element repeated twice in it
Object.froEntries will convert a list of key-value pair to an Object
This can be also done with the plain old for loop
data = ["one","two","three"];
obj = {};
for(let i = 0; i < data.length ; i++){
obj[data[i]] = data[i];
}
Try this:
const arr = ["one","two","three"]
let obj = {}
arr.forEach(item => {obj[item] = item})
document.write(JSON.stringify(obj))
Lodash has the _.keyBy() function, that creates an object from an array by generating keys from the values via the function supplied (the iteratee). The default iteratee is _.identity(), which returns the value.
const arr = ["one","two","three"];
const obj = _.keyBy(arr);
console.log(obj);
<script src="https://cdn.jsdelivr.net/npm/lodash#4.17.15/lodash.min.js"></script>

Lodash: Extract property, split array, get unique values

In my JS project, I am using Lodash library to Extract property, split array, get unique values.
var taskobj = [
{'taskno':'a', 'team':'1,2'},
{'taskno':'b', 'team':'3,4'},
{'taskno':'c', 'team':'2,4'},
];
//Looping through the object to convert string to array
_.forEach(taskobj, function(value, key) {
taskobj[key].team = _.split(taskobj[key].team,',');
});
// using _.map to extract team and return array
// using _.flatten to flatten array
// using _.uniq to get unique values from flattned array.
return _.uniq(_.flatten(_.map(taskobj,'team')));
// logs - [1,2,3,4]
Is this the most efficient way to achieve this?
you can use reduce and start with a new Set() and add the values of team every time ( then convert it back to an array with the spread operator )
var taskobj = [
{'taskno':'a', 'team':'1,2'},
{'taskno':'b', 'team':'3,4'},
{'taskno':'c', 'team':'2,4'},
];
var result = [...taskobj.reduce((acc, {team}) => {
team.split(',').forEach(e => acc.add(e))
return acc
}, new Set())]
console.log(result)
This can be achieved by using lodash#flatMap with an iteratee that splits the team string into an array, which is then flattened by the mentioned function and then use lodash#uniq to get the final result.
var result = _.uniq(_.flatMap(taskobj, ({ team }) => team.split(',')));
var taskobj = [
{'taskno':'a', 'team':'1,2'},
{'taskno':'b', 'team':'3,4'},
{'taskno':'c', 'team':'2,4'},
];
var result = _.uniq(_.flatMap(taskobj, ({ team }) => team.split(',')));
console.log(result);
.as-console-wrapper{min-height:100%;top:0}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>
Use simpler version
try this
var teams = [];
var taskobj = [
{'taskno':'a', 'team':'1,2'},
{'taskno':'b', 'team':'3,4'},
{'taskno':'c', 'team':'2,4'},
];
taskobj.map(obj => {
var teamSplit = obj.team.split(',');
teams = [...teams, ...teamSplit];
})
var uniqTeams = _.uniq(teams);
console.log('teams', teams);
console.log('uniqTeams', uniqTeams)
JsBin link
http://jsbin.com/bedawatira/edit?js,console

Convert array of strings into an array of objects

I have this JavaScript array:
[ "124857202", "500255104", "78573M104" ]
I want to convert this particular array into an array of objects as shown below:
[
{ name: "124857202" },
{ name: "500255104" },
{ name: "78573M104" }
]
Use Array#map to convert each value into a different value:
var newArr = arr.map(function(value) {
return {name: value};
});
Array#map applies the callback to each element in the array and returns a new array containing the return values of the callback.
I would take a look at the array.map function in javascript.
const mappedArr = arr.map(value => {
return {
name: value
}
})
I want to convert this particular array into an array of objects as
shown below
If you want to change the actual array in place (rather than creating a new array), you can use a for loop to iterate the indexes of your array. For each index, you can replace the value with an object {name: arr[i]}. This object has a name key, and takes a value which is the current element arr[i].
const arr = [ "124857202", "500255104", "78573M104" ];
for(let i = 0; i < arr.length; i++) {
arr[i] = {name: arr[i]};
}
console.log(arr);
Or, if you want to make a new array and leave the original untouched, you can use Felix's answer, here it can be re-written to use more modern ES6 features to make it more concise, such as an arrow function and shorthand property names:
const arr = [ "124857202", "500255104", "78573M104" ];
const res = arr.map(name => ({name}));
console.log(res);
Another approach - Array#reduce.
var arr = ["124857202", "500255104", "78573M104"];
var res = arr.reduce(function(s, a){
s.push({name: a});
return s;
}, [])
console.log(res);
You can use
var arrayOfStrings = ["124857202", "500255104", "78573M104"];
var arrayOfObjects = [];
arrayOfStrings.forEach(function (element, index) {
arrayOfObjects.push({
name: element,
})
});
Felix Kling' answer, gehsekky's answer and the second part of Nick Parsons' answer are the most correct. For completeness, here is a version that uses Underscore's _.map:
import { map } from 'underscore';
var result = map(array, name => ({name}));
For this particular use case, _.map doesn't buy you much compared to Array.prototype.map except for a little bit of added portability. Going the other way, however, is a bit easier on the brain with _.map because of Underscore's iteratee shorthands:
// Underscore map
var array = map(result, 'name');
// Array.prototype.map
var array = result.map(obj => obj.name);
Underscore's map and other collection functions really shine when you need to iterate over a plain object, since JavaScript's built-in methods don't support this at all:
var objectOfStrings = {
first: "124857202",
second: "500255104",
third: "78573M104"
};
// to array of strings, Underscore
var arrayOfStrings = map(objectOfStrings);
// to array of strings, vanilla JS
var arrayOfStrings = [], value;
for (key in objectOfStrings) {
arrayOfStrings.push(objectOfStrings[key]);
}
// to array of objects, Underscore
var arrayOfObjects = map(objectOfStrings, name => ({name}));
// to array of objects, vanilla JS
var arrayOfStrings = [], name;
for (key in objectOfStrings) {
name = objectOfStrings[key];
arrayOfStrings.push({name});
}
var objectOfObjects = {
first: {name: "124857202"},
second: {name: "500255104"},
third: {name: "78573M104"}
};
// to array of strings, Underscore
var arrayOfStrings = map(objectOfStrings, 'name');
// to array of strings, vanilla JS
var arrayOfStrings = [], value;
for (key in objectOfObjects) {
arrayOfStrings.push(objectOfObjects[key].name);
}
// to array of objects, Underscore
var arrayOfObjects = map(objectOfObjects);
// to array of objects, vanilla JS
var arrayOfObjects = [], value;
for (key in objectOfStrings) {
arrayOfObjects.push(objectOfStrings[key]);
}

Convert array of objects to plain object using Ramda

How can I convert an array of objects to a plain object?
Where each item of the array is an object with only one key:value pair and the key have an unknown name.
I have this
const arrayOfObject = [
{KEY_A: 'asfas'},
{KEY_B: 'asas' }
]
let result = {}
const each = R.forEach((item) => {
const key = R.keys(item)[0]
result[key] = item[key]
})
return result
But I dislike that solution because the forEach is using a global variable result and I'm not sure how to avoid side effects here.
Ramda has a function built-in for this, mergeAll.
const arrayOfObject = [
{KEY_A: 'asfas'}
,{KEY_B: 'asas' }
];
R.mergeAll(arrayOfObject);
//=> {"KEY_A": "asfas", "KEY_B": "asas"}
Since everybody is using ES6 already (const), there is a nice pure ES6 solution:
const arrayOfObject = [
{KEY_A: 'asfas'},
{KEY_B: 'asas'}
];
Object.assign({}, ...arrayOfObject);
//=> {KEY_A: "asfas", KEY_B: "asas"}
Object.assing merges provided objects to the first one, ... is used to expand an array to the list of parameters.
Use reduce instead:
const arrayOfObject = [
{KEY_A: 'asfas'}
,{KEY_B: 'asas' }
];
const each = R.reduce((acc,value) => {
const key = R.keys(value)[0];
acc[key] = value[key];
return acc;
},{},arrayOfObject);
Since your array is an array of objects, you could also just call merge inside a reduce:
const each2 = R.reduce((acc,value) => R.merge(value,acc),{},arrayOfObject);
Here is a jsbin with both examples:
http://jsbin.com/mifohakeru/edit?js,console,output

Categories