Convert array to object with similar key/value pairs - javascript

I have an array of values as follows
[
{
"factor": {
"data": "f1",
"val": [
"val1"
]
}
},
{
"factor": {
"data": "f2",
"val": [
"val2"
]
}
}
]
Is there a way to convert it to below format
{
"keyvalue": {
"factor": {
"data": "f1",
"val": ["val1"]
},
"factor": {
"data": "f2",
"val": ["val2"]
}
}
}
Standard array parsing to object doesn't work in this case given keys has to be unique

It's impossible. Every key in the object has to be unique. To understand this, imagine you have an object with two identical keys:
const obj = {
"key": 1,
"key": 2
}
But what you should receive when you use an expression like obj.key? 1 or 2? It's nonsense.
You should rethink your object structure, maybe you need an array of objects?
{
"keyvalue": {
"factor": [
{
"data": "f1",
"val": ["val1"]
},
{
"data": "f2",
"val": ["val2"]
}
]
}
}

What you can do is use the data field as a key given it's always unique.
Something like this :
{
"factor": {
"f1": ["val1"],
"f2": ["val2"]
}
}
Here's how you would proceed to transform the array to the key/value object :
let keyValue = {"factor": {}};
theArray.forEach((item) => {
const key = item.factor.data;
const value = item.factor.val;
keyValue.factor[key] = value;
});
now the keyValue object is as described.

Related

Problem mapping over data from API as its just an object not an array of objects in React

If I have this data structure coming from an api:
{
"value": 0,
"time": [
"2021-10-15"
],
"innerArray": [
{
"name": "string",
"Value": [
0
]
}
]
}
I am trying to access the element by:
let dataLoop = data // object from api
then I am doing:
function Loop() {
dataLoop.map((inner: any) => {
console.log('series =', inner.innerArray);
})
};
But I am getting TypeError: dataLoop.map is not a function
It is because
{
"value": 0,
"time": [
"2021-10-15"
],
"innerArray": [
{
"name": "string",
"Value": [
0
]
}
]
}
is an object, you can map only on Array type elements.
innerArray is an element on which you can .map like this:
dataLoop.innerArray.map((inner: any) => {
console.log('series =', inner);
})
to be able to map through an object you have to use Object like:
Object.entries(data).map(([key,value])=>{
console.log(key,value)
})
for example, so output would be like :

how to foreach array to array object in javascript

I'm very confused about doing foreach array to array object in Javascript, I already did a lot of research about foreach object in Javascript and I tried many ways but nothing works. All that I'm trying to achieve is to have data JSON like this :
[
{
"name": "First Data",
"data": [
{
"y": 95,
"total":100,
"md": "1",
"name": "National",
"drillup" : 'level0',
"drilldown" : "3",
"next" : "level2"
}
]
}
,{
"name": "Second Data",
"data": [
{
"y": 95,
"total":100,
"md": "1",
"name": "National",
"drillup" : 'National',
"drilldown" : "3",
"next" : "level2"
}
]
}
]
and I tried to do foreach based on some finding of my research but the result wasn't like what I want or like what I'm try to achieve ..
and here is the script that I tried :
dataFirstSecond = await informationModel.getdata();
Object.entries(dataRegularSecondary).forEach(entry => {
const [key, value] = entry;
returnData[key] = [
{
name: value.name,
data: [{
y: value.y,
total: value.total_ada,
next: 'level_2',
drilldown: true,
}]
}]
});
and here is the result or the output of my script that I try it :
{
"0": [
{
"name": "First Data",
"data": [
{
"y": 22.973,
"total": 17,
"next": "level_2",
"drilldown": true
}
]
}
],
"1": [
{
"name": "Second Data",
"data": [
{
"y": 5.4054,
"total": 4,
"next": "level_2",
"drilldown": true
}
]
}
]
}
can someone help me to achieve the data that I want?
returnData[key] = [{ ... }] should just be returnData.push({ ... }), and make sure returnData is an array (e.g. returnData = [])
If the function informationModel.getdata(); returns an Object you could use the method JSON.stringify(Object) to easily convert and Object to JSON. For example you could try to do to convert this Object to a String then cast the String to JSON.
let JSONString = JSON.stringify(informationModel.getdata());
let JSON_Object = JSON.parse(JSONString);
If dataRegularSecondary is an array and not an object you could use map:
dataRegularSecondary.map(value => {
return {
name: value.name,
data: [{
y: value.y,
total: value.total_ada,
next: 'level_2',
drilldown: true,
}]
}
}
Your question is how to forEach array to array object. Then that means dataRegularSecondary is an array, right? Object.entries returns an array of key value pairs. If you pass an array to that method, it will return the indices as keys and the items as values.
const arr = ['hello', 'world'];
Object.entries(arr); // [['0', 'hello'], ['1', 'world']]
Skip the Object.entries and use dataRegularSecondary directly for forEach.
As for your output, it looks like returnData is an object as well. Make sure it's an array and just push the data into that.
dataRegularSecondary.forEach(value => {
returnData.push({
name: value.name,
data: [{
y: value.y,
total: value.total_ada,
next: 'level_2',
drilldown: true,
}],
});
});
Or you can use map as well.
const returnData = dataRegularSecondary.map(value => ({
name: value.name,
data: [{
y: value.y,
total: value.total_ada,
next: 'level_2',
drilldown: true,
}],
}));

Restructure nested Object

I have a problem. I have an object with this structure like this example.
{
"Name": "Peter",
"Username": "dummy",
"Age": 18,
"moreData": {
"tags": [1,2,3],
"hasCar": true,
"preferences": {
"colors": ["green", "blue"]
}
}
}
I would like to convert it to an array like the following. I am desperate and can not get any further. I have issues as soon I get some nested objects. Does someone have an idea how I can achieve this? Kind Regards
[
{
"key": "Name",
"val": "Peter"
},
{
"key": "Username",
"val": "dummy"
},
{
"key": "Age",
"val": "18"
},
{
"key": "tags",
"val": [1,2,3]
},
{
"key": "hasCar",
"val": true
},
{
"key": "colors",
"val": ["green", "blue"]
}
]
For this you need to first iterate through all the key value pairs of your object and change the specific type of data into name value pairs except the nested objects. If the value in the object at a certain key is an object then the same procedure has to be done for it. And since there can be N number of levels for this nested data thus we need a recursive function for it. Whenever we have to do a same set of processing for nested data then it always means it can be done using recursion. It can be done via for loops too but a recursive function is much clear and lesser to write.
function getData(data) {
let results = [];
Object.keys(data).forEach(key => {
// If the type of the data item is object and is not an array, go into recursion
if(typeof data[key] == 'object' && !Array.isArray(data[key])) {
results = results.concat(getData(data[key]));
} else {
results.push({ key, val: data[key] });
}
});
return results;
}
const data = {
"Name": "Peter",
"Username": "dummy",
"Age": 18,
"moreData": {
"tags": [1,2,3],
"hasCar": true,
"preferences": {
"colors": ["green", "blue"]
}
}
};
const results = getData(data);
console.log(results);
// [{"key":"Name","val":"Peter"},{"key":"Username","val":"dummy"},{"key":"Age","val":18},{"key":"tags","val":[1,2,3]},{"key":"hasCar","val":true},{"key":"colors","val":["green","blue"]}]

Javascript -sort array based on another javascript object properties

I have one javascript array and one object . Need help to sort javascript object keys based on the order number in another array
In subgroup array , I have name , order number. Need to sort Offerings keys based on that order number
const subgroup = [
{
"code": "6748",
"name": "test123",
"orderNumber": "0"
},
{
"code": "1234",
"name": "customdata",
"orderNumber": "1"
}
]
const offerings = {
"customdata" : [
{
"code": "Audi",
"color": "black"
}
],
"test123" : [
{
"brand": "Audi",
"color": "black"
}
]
}
I believe this should work for you. I've added some comments in the code that should hopefully do an okay job of explaining what is happening.
var subgroup = [{
"code": "6748",
"name": "test123",
"orderNumber": "0"
}, {
"code": "1234",
"name": "customdata",
"orderNumber": "1"
}];
var offerings = {
"customdata": [{
"code": "Audi",
"color": "black"
}],
"test123": [{
"brand": "Audi",
"color": "black"
}]
}
function sortObjectFromArray(refArray, sortObject, orderKey = 'order', linkKey = 'key') {
// Get copy of refArray
let reference = refArray.slice();
// Sort sortObject [ into an array at this point ]
let sorted = [];
for (let key in sortObject) {
// Searches the refArray for the linkKey, and returns the intended index
let index = reference.find((item) => item[linkKey] === key)[orderKey];
// Places the sortObject's value in the correct index of the 'sorted' Array
sorted[parseInt(index)] = [key, sortObject[key]];
};
// Return an object, created from previous 'sorted' Array
return sorted.reduce((obj, [key, value]) => {
obj[key] = value;
return obj;
}, {});
};
offerings = sortObjectFromArray(subgroup, offerings, 'orderNumber', 'name');
console.log(offerings);

group by/formatting json data in Javascript

Sorry if this has been asked before. I have the JSON structure like:
{"data":[
{"Date":"03/04/2016","Key":"A","Values":"123"},
{"Date":"04/04/2016","Key":"A","Values":"456"},
{"Date":"03/04/2016","Key":"B","Values":"789"},
{"Date":"04/04/2016","Key":"B","Values":"012"}
]}
I want to change this to a different format which is basically grouped by Key and combines rest of the field in Values
{"Result":[
{
"Key":"A"
"Values":[["03/04/2016","123"], ["04/04/2016","456"]]
},
{"Key":"B"
"Values":[["03/04/2016","789"]},["04/04/2016","012"]]
}
]}
I want to do this javascript/html
You could iterate and build a new object if not exist.
var object = { "data": [{ "Date": "03/04/2016", "Key": "A", "Values": "123" }, { "Date": "04/04/2016", "Key": "A", "Values": "456" }, { "Date": "03/04/2016", "Key": "B", "Values": "789" }, { "Date": "04/04/2016", "Key": "B", "Values": "012" }], result: [] };
object.data.forEach(function (a) {
if (!this[a.Key]) {
this[a.Key] = { Key: a.Key, Values: [] };
object.result.push(this[a.Key]);
}
this[a.Key].Values.push([a.Date, a.Values]);
}, Object.create(null));
console.log(object);
I think this can be a better answer (but Nina's answer is the match for your problem terms) if items of data array have different properties and you don't want to change input data.
var raw = {"data":[
{"Date":"03/04/2016","Key":"A","Values":"123"},
{"Date":"04/04/2016","Key":"A","Values":"456"},
{"Date":"03/04/2016","Key":"B","Values":"789"},
{"Date":"04/04/2016","Key":"B","Values":"012"}
]};
var result = new Map;
raw.data.forEach(entry => {
var key = entry.Key;
if (this[key])
return this[key].push(getClonedData(entry));
this[key] = [getClonedData(entry)];
result.set(key, {
Key: key,
Values: this[key]
})
}, Object.create(null));
var filtered = {
result: [...result.values()]
}
console.log(filtered);
function getClonedData(entry) {
data = Object.assign({}, entry);
delete data.Key;
return data;
}

Categories

Resources