Rearrange dynamic Object to form a structured Object - javascript

I have an Object like this:
const val = {"abc":{"1":1, "2":6,"3":5},"def":{"1":3, "2":4,"3":8},"xyz":{"1":5, "2":6,"3":7}}
I want to transform the object data like below:
[{"abc":1,"def":3,"xyz":5},{"abc":6,"def":4,"xyz":6}, ...]
All the values are dynamic, any number of inner object may be there
I have tried like this:
const val = {"abc":{"1":1, "2":6,"3":5},"def":{"1":3, "2":4,"3":8},"xyz":{"1":5, "2":6,"3":7}}
let dataObj = {};
let secondArr = [];
let dataArr =[]
Object.entries(val).map(firstObj=>{
Object.entries(firstObj[1]).forEach(secondObj => {
dataObj={[firstObj[0]]:secondObj[1]};
secondArr.push(dataObj);
})
dataArr.push(secondArr)
})
console.log(dataArr)
Can anyone tell me a solution for this?
Thanks in advance

You could iterate the entries of the objects and take the inner keys as indices of the array with new objects with outer key and value.
var data = { abc: { 1: 1, 2: 6, 3: 5 }, def: { 1: 3, 2: 4, 3: 8 }, xyz: { 1: 5, 2: 6, 3: 7 } },
result = Object
.entries(data)
.reduce((r, [k, o]) => {
Object.entries(o).forEach(([i, v]) =>
Object.assign(r[i - 1] = r[i - 1] || {}, { [k]: v }));
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Related

Convert array to map with predefined keys

I have an data in an array that looks like that:
let data = {[val1, val2, val3], [val4, val5, val6]}
I need to convert it to a map with predefined keys:
let keys = [key1, key2, key3]
I would like my output to be key-value map like this:
0: {key1:value1, key2:value2, key3:value3}
1: {key1:value4, key2:value5, key3:value6}
I tried:
let obj = Object.assign(keys, data)
But output is:
0: (3) [value1, value2, value3]
1: (3) [value4, value5, value6]
Use Object.fromEntries and map
const data = [
[1, 2, 3],
[4, 5, 6]
];
const keys = ["key1", "key2", "key3"];
const updated = data.map(arr =>
Object.fromEntries(arr.map((item, i) => [keys[i], item]))
);
console.log(updated);
You can make use of .map() and .reduce() functions to get the desired output:
let data = [['val1', 'val2', 'val3'], ['val4', 'val5', 'val6']];
let keys = ['key1', 'key2', 'key3'];
let result = data.map(
vals => vals.reduce((r, c, i) => (r[keys[i]] = vals[i], r), {})
);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Simple solution.
let data = [
[1, 2, 3],
[4, 5, 6]
];
let keys = ["key1", "key2", "key3"];
const res = data.map(([v1, v2, v3]) => {
return {
[keys[0]]: v1,
[keys[1]]: v2,
[keys[2]]: v3
};
});
console.log(res);
// Also
const res2 = data.map(arr => {
let map = {};
keys.forEach((key, index) => {
map[key] = arr[index];
});
return map;
});
console.log(res2);
// Also
const res3 = data.map(arr =>
keys.reduce((o, key, index) => {
o[key] = arr[index];
return o;
}, {})
);
console.log(res3);
.as-console-wrapper { max-height: 100% !important; top: 0; color: blue; background: #fff}

Mapping key and value to new keys in Javascript

Array of dictionaries should be converted simpler form.
data = [{A:1},{B:2},{C:3}]
data = {A: 1, B: 2}
data = ["0":{ A : 1, B : 2 , C : 3}]
Both are completely different datasets. I'm trying to map it also like below format.
The above should become like
data = [
{
name: "A",
y: 1
},
{
name: "B",
y: 2
},
{
name: "C",
y: 3
}
];
I tried this following approach but it's wrong
name = {}
data.forEach(function(k,x){
return name['name'] = k , name["y"] = x
})
Please suggest me a better approach.
map each object's entries to extract the key and the value, and return an object with name and y keys:
const data = [{A:1},{B:2},{C:3}]
const output = data.map(item => {
const [name, y] = Object.entries(item)[0];
return { name, y };
});
console.log(output);
If the keys (A, B, etc) are guaranteed to be unique throughout the array, then everything becomes simpler.
const data = [{A:1},{B:2},{C:3}];
const merged = Object.assign({}, ...data);
const newData = Object.entries(merged)
.map(([name, y]) => ({ name, y }));
console.log(newData);
However, if the keys aren't guaranteed unique, then refer to CertainPerformance's answer.
you can implement like this
var data = [{A:1},{B:2},{C:3}];
var reformattedArra = data.map(obj => {
let val = {};
val.name = Object.keys(obj)[0];
val.y = obj[Object.keys(obj)[0]];
return val;
})
console.log(JSON.stringify(reformattedArra));
I would say, use Object.keys() which is widly supported
let data = [{A:1},{B:2},{C:3}];
data = Object.assign({}, ...data);
data = Object.keys(data).map(key => ({ name: key, y: data[key] }));
console.log(data);
You yould could chekc the data format and if it is not an array, build one and reduce the array by taking the objetcs and create for each key/value a new object for the result set.
function simple(data) {
return (Array.isArray(data) ? data : [data]).reduce((r, o) => [...r, ...Object.entries(o).map(([name, y]) => ({ name, y }))], []);
}
console.log(simple([{ A: 1 }, { B: 2 }, { C: 3, D: 4 }]));
console.log(simple({ A: 1, B: 2 }));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Reduce JavaScript Objects into Array of Formatted Objects

I have an array of objects in the format
{type: number, sub_type: number}
I need to sort them into an array of objects formatted like this
{
type_id: (type from at least one object in array above),
sub_types: [
(all sub types from objects in array above that match this type)
]
}
This is what I came up but I think there is a more efficient way. rawTypes is an array of objects in need of formatting, types ends up being the array of formatted objects.
const typeIds = [...new Set(rawTypes.map(val => val.type))];
const types = typeIds.map(val => ({type_id: val, sub_types: [] }));
rawTypes.forEach(obj => {
let typeIndex = types.reduce((accum, val, i) => val.type_id === obj.type ? i : accum, 0);
types[typeIndex].sub_types.push(obj.sub_type);
});
I think a better solution would use recursion but I can't think of how to do it.
Look at this approach
var data = [{type: 5, sub_type: 10}, {type: 5, sub_type: 11}, {type: 6, sub_type: 12}];
var obj = data.reduce((a, c) => {
var current = a[`type_id_${c.type}`];
if (current) {
current.sub_types.push(c.sub_type);
} else {
var key = `type_id_${c.type}`;
a = { ...a, ...{ [key]: {sub_types: [c.sub_type], 'key': c.type} } };
}
return a;
}, {});
var array = Object.keys(obj).map((k) => ({ 'type': obj[k].key, 'subtypes': obj[k].sub_types }));
console.log(array)
.as-console-wrapper {
max-height: 100% !important
}

how to unwind javascript object into Json object without duplicate entries

existingJsObj = {"a": [1,2,3,4], "b":[11,22,33,44]}
I want to convert this javascript into something that doesnt have array items in it, like below
desiredJsObj = [{"a":1, "b":11},{"a":2,"b":22},{"a":3, "b":33},{"a":4, "b":44}]
You could iterate the keys and the values while using a new array and object for the result.
var object = { a: [1, 2, 3, 4], b: [11, 22, 33, 44] },
array = Object.keys(object).reduce(function (r, k) {
object[k].forEach(function (v, i) {
(r[i] = r[i] || {})[k] = v;
});
return r;
}, []);
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
I would do following:
const income = {"a": [1,2,3,4], "b":[11,22,33,44]};
const res = income.a.map((a, i) => ({ a: a, b: income.b[i] }));
This works in assumption that "a" length is equal to "b" length.
try this
existingJsObj = {"a": [1,2,3,4], "b":[11,22,33,44]}
desiredJsObj = []
keys = Object.keys(existingJsObj);
existingJsObj[keys[0]].forEach((val, index) => {
value = {};
keys.forEach((key, i) => value[key] = existingJsObj[key][index])
desiredJsObj.push(value)
})

How can I add name to existing value pair in json

Hello this is my sample json:
{
"2016-01-01T00:00:00Z": 1,
"2016-02-01T00:00:00Z": 2,
"2016-03-01T00:00:00Z": 3
}
Now I want something like
[
{"Month":"2016-01-01T00:00:00Z", "Number": 1},
{"Month":"2016-02-01T00:00:00Z", "Number": 2},
{"Month":"2016-03-01T00:00:00Z", "Number": 3}
]
How can I do this using JS/Jquery? I wanted to change it to the above mentioned format because I need to put them in html table and I found out that using the second format makes my job easier.
you can do this in the following way
let obj = {
"2016-01-01T00:00:00Z": 1,
"2016-02-01T00:00:00Z": 2,
"2016-03-01T00:00:00Z": 3
};
let result = [];
for(element in obj){
result.push({"Month":element, "Number": obj[element]})
}
console.log(result);
You can use the jQuery map function to change the format of an array.
let jsonArray = {
"2016-01-01T00:00:00Z": 1,
"2016-02-01T00:00:00Z": 2,
"2016-03-01T00:00:00Z": 3
};
var result = $.map(jsonArray, function (item, key) {
return {
Month: key,
Number: item
};
});
You could take the keys with Object.keys and use Array#map for mapping the new objects.
var object = { "2016-01-01T00:00:00Z": 1, "2016-02-01T00:00:00Z": 2, "2016-03-01T00:00:00Z": 3 },
result = Object.keys(object).map(function (k) {
return { Month: k, Number: object[k] };
});
console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }
var object1 = {
"2016-01-01T00:00:00Z": 1,
"2016-02-01T00:00:00Z": 2,
"2016-03-01T00:00:00Z": 3
};
var finalArray = [];
for (var key in object1) {
if (p.hasOwnProperty(key)) { // p.hasOwnProperty this will check for duplicate key
finalArray.push({
“Month” : key,
“Number”:p[key]
});
}
}
console.log(finalArray)
Another option could include using Object.keys along with map as such...
let obj = {
'2016-01-01T00:00:00Z': 1,
'2016-02-01T00:00:00Z': 2,
'2016-03-01T00:00:00Z': 3
}
let arr = Object.keys(obj).map(key => {
return {'Month': key, 'Number': obj[key]}
});
JSFiddle demo
use $.each for travelling
a = {
"2016-01-01T00:00:00Z": 1,
"2016-02-01T00:00:00Z": 2,
"2016-03-01T00:00:00Z": 3
}
var b = [];
$.each( a, function( key, value ) {
b.push({mounth: key ,number: value });
});
Output will be:
0:{mounth: "2016-01-01T00:00:00Z", number: 1}
1:{mounth: "2016-02-01T00:00:00Z", number: 2}
2:{mounth: "2016-03-01T00:00:00Z", number: 3}

Categories

Resources