Convert Flat JSON Array to JSON Object in Nodejs - javascript

I have a flat json array that store data like this:
[
{
"prop1": "prop1Data1"
},
{
"prop2": "prop2Data1"
},
{
"prop3.name": "Tom"
}
]
How can I convert this data into simple json object in node js like this:
{ "prop1": "prop1Data1", "prop2": "prop2Data1", "prop3.name": "Tom" }

You could use Object.assign and use spread syntax ... for the array.
var array = [{ prop1: "prop1Data1" }, { prop2: "prop2Data1" }, { "prop3.name": "Tom" }],
object = Object.assign({}, ...array);
console.log(object);
ES5 with Array#reduce and by iterating the keys.
var array = [{ prop1: "prop1Data1" }, { prop2: "prop2Data1" }, { "prop3.name": "Tom" }],
object = array.reduce(function (r, o) {
Object.keys(o).forEach(function (k) {
r[k] = o[k];
});
return r;
}, {});
console.log(object);

The way that I've done it was like so, since it is within an array.
var original = [{"prop1": "prop1Data1"},{"prop2": "prop2Data1"},{"prop3.name": "Tom"}];
var propStore = {
prop1 : '',
prop2 : '',
prop3 : ''
}
propStore.prop1 = original[0]["prop1"];
propStore.prop2 = original[0]["prop2"];
propStore.prop3 = original[0]["prop3"];
console.log(propStore);

Related

Converting to Correct Object Format from Array

I am aware of options like the spread operator and Object.assign() when it comes to converting an array to an object, however, I am having difficulty figuring out how to format the final object in the format I need.
My original array looks like this:
let propsArray = [ { id: '1' },
{ 'name.first': 'john' },
{ 'name.last': 'smith' } ]
The object I want from this data needs to look like this:
{
"id" : 1,
"name" : {
"first" : "john",
"last" : "smith"
}
}
What I've tried so far, using object.assign(), ends up adding numbers as property keys in the resulting object, which is clearly not what I'm looking for:
let finalObj = Object.assign({}, propsArray);
How can I get the resulting object formatted the way I need here?
You need a deeper look into the object and take the splitted key and reduce them by taking an object with the property or an empty object. At the end assign the value.
var data = [{ id: '1' }, { 'name.first': 'john' }, { 'name.last': 'smith' }],
result = data.reduce((r, o) => {
Object.entries(o).forEach(([k, v]) => {
var keys = k.split('.'),
last = keys.pop();
keys.reduce((q, k) => q[k] = q[k] || {}, r)[last] = v;
});
return r;
}, {});
console.log(result);
Try this:
const data = [
{
"id": "1"
},
{
"name.first": "john"
},
{
"name.last": "smith"
}
]
const result = Object.entries(Object.assign({}, ...data))
.reduce((acc,[k,v])=>{
[first, last] = k.split('.');
if (!last) {
acc[k] = v
} else {
acc[first] = acc[first] || {};
acc[first][last] = v;
}
return acc
}, {})
console.log(result);

Es6 way to convert object key value to one single object

I want to convert all data into one object,
let d = {
"Coupon_Code": "code",
"Coupon_Name": "namie",
"Coupon_Desc": 1000,
"selectedCity": [
{
"Coupon_City_Name": "xyz"
}
],
"selectedCategory": [
{
"Coupon_Category_Name": "Shopping"
}
],
"selectedCompany": [
{
"Coupon_Company_Name": "Shopper Stop"
}
],
"selectedState": [
{
"Coupon_State_Name": "abc"
}
],
"Coupon_Date": "2222-02-22",
}
i tried some methods of Object like keys , entries but dont no what to use.
Final output should be
let d = {
Coupon_Code: "code",
Coupon_Name: "namie",
Coupon_Desc: 1000,
Coupon_City_Name: "xyz",
Coupon_Category_Name: "Shopping",
Coupon_Company_Name: "Shopper Stop",
Coupon_State_Name: "abc",
Coupon_Date: "2222-02-22",
};
what's the best and optimum way to have above result using Venila Js and Es6
Reduce the entries of the original object. If the entry's value is an array merge the 1st element, if not merge the original key and value. You can merge the properties into the object using object spread:
const data = {"Coupon_Code":"code","Coupon_Name":"namie","Coupon_Desc":1000,"selectedCity":[{"Coupon_City_Name":"xyz"}],"selectedCategory":[{"Coupon_Category_Name":"Shopping"}],"selectedCompany":[{"Coupon_Company_Name":"Shopper Stop"}],"selectedState":[{"Coupon_State_Name":"abc"}],"Coupon_Date":"2222-02-22"};
const result = Object.entries(data)
.reduce((r, [k, v]) => ({
...r,
...Array.isArray(v) ? v[0] : { [k]: v }
}), {});
console.log(result);
You can use Array.reduce and Object.entries
let d = {"Coupon_Code":"code","Coupon_Name":"namie","Coupon_Desc":1000,"selectedCity":[{"Coupon_City_Name":"xyz"}],"selectedCategory":[{"Coupon_Category_Name":"Shopping"}],"selectedCompany":[{"Coupon_Company_Name":"Shopper Stop"}],"selectedState":[{"Coupon_State_Name":"abc"}],"Coupon_Date":"2222-02-22"};
d = Object.entries(d).reduce((a,[k,v]) => {
// If the value is an array, iterate over it to merge into the resultant object
if(Array.isArray(v)) Object.assign(a, ...v)
else Object.assign(a, {[k]:v}) // if it is not an array, merge into resultant object
return a;
}, {});
console.log(d);
You could take a recursive approach.
const
fn = o => Object.assign(...Object.entries(o).map(([k, v]) => Array.isArray(v) ? Object.assign(...v.map(fn)) : { [k]: v })),
d = { Coupon_Code: "code", Coupon_Name: "namie", Coupon_Desc: 1000, selectedCity: [{ Coupon_City_Name: "xyz" }], selectedCategory: [{ Coupon_Category_Name: "Shopping" }], selectedCompany: [{ Coupon_Company_Name: "Shopper Stop" }], selectedState: [{ Coupon_State_Name: "abc" }], Coupon_Date: "2222-02-22" },
result = fn(d);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
A possible iterative solution is:
function flatten(obj) {
let r = {}
for (let [key, value] of Object.entries(obj)) {
if (Array.isArray(value)) {
Object.assign(r, value[0]);
} else {
Object.assign(r, {[key]: value});
}
}
return r;
}
Something like this:
const d = { Coupon_Code: "code", Coupon_Name: "namie", Coupon_Desc: 1000, selectedCity: [{ Coupon_City_Name: "xyz" }], selectedCategory: [{ Coupon_Category_Name: "Shopping" }], selectedCompany: [{ Coupon_Company_Name: "Shopper Stop" }], selectedState: [{ Coupon_State_Name: "abc" }], Coupon_Date: "2222-02-22" };
function toSingleObj(obj) {
var result = {};
Object.entries(obj).forEach(([key,value]) => {
if (Array.isArray(value)) {
Object.entries(value[0]).forEach(([k,v]) => {
result[k] = v;
});
} else {
result[key] = value;
}
});
return result;
}
console.log("Result: ", toSingleObj(d));

javascript,lodash:- how to sort array of objects where object having object inside

var a = [
{
"subObj1": {
"key1":10722905,
"key2":"0080817626"
},
"outerKey1":"abcd",
"outerKey2":"defg"
},
{
"subObj1": {
"key1":123456,
"key2":"0987654"
},
"outerKey1":"pqrs",
"outerKey2":"ased"
}
]
i need to sort this array of object using key1 and outerkey1 both separately. That logic is already implemented.
_.sortBy(a,'outerKey1') -> this is working fine.
_.sortBy(a,'key1') -> this is not working.
_.sortBy(a,'subObj1.key1') -> this is also not working.
Is there any way to sort this array of objects with inner key of object like key1 or key2 using lodash _.sortBy function?
Using only JavaScript you can use Array.prototype.sort() along with a custom callback fucntion:
var sorted = arr.sort(function(a, b) {
a.subObj1.key1 - b.subObj1.key1
});
Demo:
var arr = [{
"subObj1": {
"key1": 10722905,
"key2": "0080817626"
},
"outerKey1": "abcd",
"outerKey2": "defg"
},
{
"subObj1": {
"key1": 123456,
"key2": "0987654"
},
"outerKey1": "pqrs",
"outerKey2": "ased"
}
];
var sorted = arr.sort(function(a, b) {
a.subObj1.key1 - b.subObj1.key1
});
console.log(sorted);
Edit:
If you you wnat to do it with lowdash, you can use _.sortBy() with a custom sorter function:
var customSorter = function(obj) {
return obj.subObj1.key1;
};
var sorted = _.sortBy(arr, customSorter);
Demo:
var arr = [{
"subObj1": {
"key1": 10722905,
"key2": "0080817626"
},
"outerKey1": "abcd",
"outerKey2": "defg"
},
{
"subObj1": {
"key1": 123456,
"key2": "0987654"
},
"outerKey1": "pqrs",
"outerKey2": "ased"
}
];
var customSorter = function(obj) {
return obj.subObj1.key1;
};
var sorted = _.sortBy(arr, customSorter);
console.log(sorted);
<script src="http://underscorejs.org/underscore-min.js"></script>

changing an array of javascript objects with a single key to an array that contains the objects' data

I currently have data in the following format:
var anArray = [
obj1: {
key1: data1
},
obj2: {
key2: data2
},
];
I would like the data to instead be in the following format:
var array2 = [data1, data2];
for some reason, I cannot figure out a concise way to to this. I know it could be done with a forEach loop that iterates over each object and pushes it onto a new array, but I would prefer to be more elegant (and shorter if possible) than that.
const anArray = {
obj1: {
key1: "A"
},
obj2: {
key2: "B"
},
};
const result = Object.keys(anArray).map(key => {
const obj = anArray[key];
return Object.keys(obj).map(key => obj[key])[0];
});
console.log(result);
Given that anArray is actually properly structured to be valid, then you could do the following:
Note that in this case anArray isn't an actual array but rather a object literal
var anArray = {
obj1: {
key1: "data1"
},
obj2: {
key2: "data2"
},
};
var array2 = []
for(i in anArray){
for(j in anArray[i]){
array2.push(anArray[i][j])
}
}
console.log(array2)
https://jsfiddle.net/wh4r0w5s/
Try with:
const arr1 = [
{key1:'value1'},
{key2:'value2'}
]
const res = arr1.map(obj => {
return Object.keys(obj).map(val => obj[val])
}).reduce((acc,v) => {
return acc.concat(v);
},[]);
console.log(res);
update
But if you have the following form:
var anArray = [
obj1: {
key1: data1
},
obj2: {
key2: data2
},
];
It's better to apply a recursive function, as follow:
const arr1 = [
{
obj1:{key1:'value1',key3:'value3'}
},
{
obj2:{key2:'value2'}
}
]
const getValuesFromObj = (obj) => {
if(typeof obj === 'string')
return obj;
return Object.keys(obj).map(key => {
return getValuesFromObj(obj[key]);
}).reduce((acc,v) => {
return acc.concat(v);
},[]);
}
const r2 = getValuesFromObj(arr1);
console.log(r2);

Javascript Nested Literal to string

I am looking for a technique to run over a object of nested properties and wish to join the properties'.
This is the object I'd like to join:
var array = {
prop1: {
foo: function() {
// Your code here
}
},
prop2: {
bar1: 'some value',
bar2: 'some other value'
}
};
The result should look like this:
[
[ 'prop1', 'foo' ],
[ 'prop2', 'bar1' ],
[ 'prop2', 'bar2' ]
]
Then I'd like to join the array to strings formatted like this:
prop1.foo
prop2.bar1
prop2.bar2
Any tips?
EDIT: Forgot to say it should work for deeper arrays too.
Something along these lines? http://jsfiddle.net/X2X2b/
var array = {
prop1: {
foo: function() {
// Your code here
}
},
prop2: {
bar1: 'some value',
bar2: 'some other value'
}
};
var newA = [],
newB = [];
for ( var obj in array ) {
for (var inObj in array[obj]) {
newA.push([obj, inObj]);
newB.push(obj + '.' + inObj);
}
}
console.log(newA);
console.log(newB);
This is quite a different problem now that you have specified that it needs to support arbitrary depths. In order to solve it we need to use recursion and we need to use a second recursive parameter which keeps track of where we are in the nested hierarchy.
function objectPropertiesToArrays(obj, prepend) {
// result will store the final list of arrays
var result = [];
// test to see if this is a valid object (code defensively)
if(obj != null && obj.constructor === Object) {
for (var propertyName in obj) {
var property = obj[propertyName],
// clone prepend instantiate a new array
list = (prepend || []).slice(0);
// add the property name to the list
list.push(propertyName);
// if it isn't a nested object, we're done
if (property.constructor !== Object) {
result.push(list);
// if it is a nested object, recurse
} else {
// recurse and append the resulting arrays to our list
result = result.concat(objectPropertiesToArrays(property, list));
}
}
}
return result;
}
Example:
var obj = {
prop1: {
foo: function() { }
},
prop2: {
bar1: 'some value',
bar2: 'some other value'
},
prop3: {
x: {
y: [],
z: 'test'
},
erg: 'yar'
}
};
objectPropertiesToArrays(obj);
Returns
[
["prop1", "foo"],
["prop2", "bar1"],
["prop2", "bar2"],
["prop3", "x", "y"],
["prop3", "x", "z"],
["prop3", "erg"]
]

Categories

Resources