How to convert object containing Objects into array of objects - javascript

This is my Object
var data = {
a:{"0": "1"},
b:{"1": "2"},
c:{"2": "3"},
d:{"3": "4"}
};
This is the output that I expect
data = [
{"0": "1"},
{"1": "2"},
{"2": "3"},
{"3": "4"}
]

This works for me
var newArrayDataOfOjbect = Object.values(data)
In additional if you have key - value object try:
const objOfObjs = {
"one": {"id": 3},
"two": {"id": 4},
};
const arrayOfObj = Object.entries(objOfObjs).map((e) => ( { [e[0]]: e[1] } ));
will return:
[
{
"one": {
"id": 3
}
},
{
"two": {
"id": 4
}
}
]

var data = {
a:{"0": "1"},
b:{"1": "2"},
c:{"2": "3"},
d:{"3": "4"}
};
var myData = Object.keys(data).map(key => {
return data[key];
})
This works for me

The accepted answer doesn't take into account the OP wanted to get rid of the keys. This returns only the objects, not their parent key.
Object.entries(ObjOfObjs).map(e => e[1]) outputs:
[
{"0": "1"},
{"1": "2"},
{"2": "3"},
{"3": "4"}
]

You can easily do this by using Object.values() function
var data = {
a:{"0": "1"},
b:{"1": "2"},
c:{"2": "3"},
d:{"3": "4"}
};
console.log(Object.values(data))

You would have to give a name to each value in the object.
Once you fix the first object, then you can do it using push.
var data = {
1: {"0": "1"},
2: {"1": "2"},
3 : {"2": "3"},
4: {"3": "4"}
};
var ar = [];
for(item in data){
ar.push(data[item]);
}
console.log(ar);
http://jsfiddle.net/nhmaggiej/uobrfke6/

this is simple and will do in an immutable way so that your main data not touched but you can create a new mappedData as per your requirement and create a new array.
let data = {
a: { "0": "1" },
b: { "1": "2" },
c: { "2": "3" },
d: { "3": "4" }
};
const mappedDataArray = [];
for (const key in data) {
const mappedData = {
...data[key]
};
mappedDataArray.push(mappedData);
}
console.log(mappedDataArray);
console.log(data);

var array = [];
for(var item in data){
// this condition is required to prevent moving forward to prototype chain
if(data.hasOwnProperty(item)){
array.push(data[item]);
}
}

Finally, It works for me to convert from object to array of objects when you get object value from
const snapshortObject = snapshot.val(); // And they look like this are stored value.
let snapshortObject = {
a: {
message: "Hiiii",
senderId: "tQusPaBhoJXcu2ezlsDxQMUTLCq1",
timestamp: "Wed Jun 8 18:16:18 2022"
},
b: {
message: "Hiiii",
senderId: "tQusPaBhoJXcu2ezlsDxQMUTLCq1",
timestamp: "Wed Jun 8 18:16:18 2022"
},
c: {
message: "Hello 👋👋👋👋",
senderId: "tQusPaBhoJXcu2ezlsDxQMUTLCq1",
timestamp: "Wed Jun 8 18:16:50 2022"
},
d: {
message: "Hello 👋👋👋👋",
senderId: "tQusPaBhoJXcu2ezlsDxQMUTLCq1",
timestamp: "Wed Jun 8 18:16:50 2022"
}
};
const mappedDataArray = [];
slno=1
for (const key in snapshortObject) {
const mappedData = {
...snapshortObject[key],
slno:slno++
};
mappedDataArray.push(mappedData);
}
console.log(mappedDataArray);

I get what you want ! Here is your solution,
var dataObject=[{name:'SrNo',type:'number'}];
And to access or store the array use
dataObject[0].srno=1;
dataObject[0].srno=2;
Hope this is what you needed.

This worked for me. And it seems to be well supported.
toArray(obj_obj) {
return Object.keys(obj_obj).map(i => obj_obj[i]);
}
https://medium.com/chrisburgin/javascript-converting-an-object-to-an-array-94b030a1604c

We can use Object default methods (Object.assign(), Object.values()) to convert Object of Object to array in the following way
const ObjValue = {
a:{"0": "1"},
b:{"1": "2"},
c:{"2": "3"},
d:{"3": "4"}
}
const ObjtoArray = (obj) => Object.assign([], Object.values(obj))
console.log(ObjtoArray(ObjValue))

Related

Split object keys with same prefix to new objects

For example, given an object with keys and values
{
prefix_1_a: 1a,
prefix_1_b: 1b,
prefix_2_a: 2a,
prefix_2_b: 2b,
}
I want convert into two objects:
prefix_1 with keys and values {a: 1a, b: 1b}
prefix_2 with keys and values {a: 2a, b: 2b}
another example ,given a formData object:
["item_0_orange":"10",
"item_0_apple:"20",
"item_0_grape":"30",
"item_1_orange":"40",
"item_1_apple":"50",
"item_1_grape":"60",
"item_2_orange":"40",
"item_2_apple":"50",
"item_2_grape":"60"]
and I want to convert to json object
fruitprice:
[
{key:0 ,orange:"10" , apple:"20" , grape:"30" },
{key:1 ,orange:"40" , apple:"50" , grape:"60" },
{key:2 ,orange:"40" , apple:"50" , grape:"60" }
]
how to search and add key and value under a position when match same prefix
here is my code:
var fruitObject ={};
for(i=0;i<3;i++)
{
var prefix = "item_" + i;
var res = key.split("_");
var newKey = res[2];
if(key.startsWith(prefix))
{
var newObject = {};
newObject[newKey] =value;
addObject(res[1],newObject, fruitObject); //by given key
return;
};
}
It can be a costly transformation, but not that complex:
Let's start with the input:
const data = {
"item_0_orange": "10",
"item_0_apple": "20",
"item_0_grape": "30",
"item_1_orange": "40",
"item_1_apple": "50",
"item_1_grape": "60",
"item_2_orange": "40",
"item_2_apple": "50",
"item_2_grape": "60",
}
Then have a look at the desired output:
const fruitprices = [
{
key: 0,
orange: "10",
apple: "20",
grape: "30"
},
{
key: 1,
orange: "40",
apple: "50",
grape: "60",
},
{
key: 2,
orange: "40",
apple: "50",
grape: "60",
}
]
And here's a transformation from data to fruitprices:
// this is an Object, not an Array!
const data = {
"item_0_orange": "10",
"item_0_apple": "20",
"item_0_grape": "30",
"item_1_orange": "40",
"item_1_apple": "50",
"item_1_grape": "60",
"item_2_orange": "40",
"item_2_apple": "50",
"item_2_grape": "60",
}
// transform function
const fruitprices = Object.entries(data).reduce((a, [key, val]) => {
// destructuring the key; "prefix" is not going to be used
const [prefix, outkey, fruit] = key.split('_')
// trying to find the item in the "a" Array
const item = a.find(({
key: itemkey
}) => itemkey === outkey)
if (item) { // if the key is already in the "a" Array
item[fruit] = val
} else { // if the key is not in the "a" Array yet
a.push({
key: outkey,
[fruit]: val
})
}
return a
}, [])
console.log(fruitprices)

How to merge multiple json arrays into one array swift sub array in Javascript?

I have two json arrays :
1)
[
{
"userId": 9
},
{
"userId": 14
}
]
2)
[{"role": "1", "group": "3"}, {"role": "1", "group": "2"}]
I would like to merge two arrays like as follows :
Is it possible to have the solution by javascript?
[
{"userId":9,"role":"1","group":"2"},
{"userId":14,"role":"1","group":"2"}
{"userId":9,"role":"1","group":"3"},
{"userId":14,"role":"1","group":"3"}
]
I tried to use Let however I couldn't find the way to manipulate switch the subarray :
let arr1 =
[{ "userId": 9 }, { "userId": 14 }]
let arr2 = [{"role": "1","group": "3"}, {"role": "1","group": "2" }]
let result = arr1.map(o => Object.assign(o, ...arr2));
console.log(result);
return result;
The result is like this :
[{"userId":9,"role":"1","group":"2"},{"userId":14,"role":"1","group":"2"}]
Thanks in advance.
You can use .map() with Object.assign():
let arr1 = [{"userId": 9}, {"userId": 14}],
arr2 = [{"rid": 1}, {"mid": 201}];
let result = arr1.map(o => Object.assign(o, ...arr2));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
#Mohammad Usman has a better answer but one simpler to understand is to create a new object with the desired values and push it into the resulting array. Something as follows:
users = [
{"userId": 9},
{"userId": 14}
];
data = [
{"rid": 1},
{"mid": 201}
];
result = [];
for (var i = 0; i < users.length; i++) {
result.push({
"rid": data[0].rid,
"mid": data[1].mid,
"userId": users[i].userId
});
}
Here result will have the desired output.

TypeScript- How to add a Key Value pair to each object in an Array?

I have an array of dates and an array of objects. I'd like to add the dates to the array of objects as a key value pair {"Date": "10-12-18"}.
dates:
["10-12-18", "10-13-18", 10-14-18"]
data:
[
{"name":"One", "age": "4"},
{"name":"Two", "age": "5"},
{"name":"Three", "age": "9"}
]
I want something like...
[
{"name":"One", "age": "4", "Date": "10-12-18"},
....
How can I do this in TypeScript? I'm used to normal JavaSCript and can't get it right.
Something I have so far:
for (let idx of data){
data[idx].date = dates[idx]
}
Thanks!!
What's wrong with your code is that idx will be the object not the index as you are using for...of. Use a simple regular for like:
for(let idx = 0; idx < data.length; idx++) {
data[idx].date = dates[idx];
}
Or use forEach to loop one of the arrays and use the index it provides to get the value from the other array:
data.forEach((obj, i) => obj.date = dates[i]);
const result = data.map(({ name, age }, index) => ({ name, age, date: dates[index] }));
just map the array to the result.
Something like that:
let dates = ["10-12-18", "10-13-18", "10-14-18"];
let objs = [{"name":"One",
"age": "4"},
{"name":"Two",
"age": "5"},
{"name":"Three",
"age": "9"}
]
const result = objs.map((item, index) => {
item.Date = dates[index];
return item;
});
console.log(result);
In TS, you can do this like below..
var data = [{
"name": "One",
"age": "4"
},
{
"name": "Two",
"age": "5"
},
{
"name": "Three",
"age": "9"
}
];
var dates = ["10-12-18", "10-13-18", "10-14-18"];
console.log(data.map((ob, i) => ({ ...ob,
"Date": dates[i]
})));

Check JSON data element value and return "" if Null for a multidimensional non-symmetrical JSON structure

I have an external data source that sometimes returns a value of null, i do not have access to this data source so i cannot change it. My Angular 2 app crashes on a undefined or null value when trying to display the data. I am trying to create a function that catches null or undefined values and sets them to an empty string.
I have found examples for symmetrical JSON structures, but not non-symmetrical nested loop structures
// JSON ARRAY EXAMPLE
[
{
"a":"1",
"x":null,
"y":[
{"k": "3"},
{"i": "5"}
]
},
{
"a":"1",
"x":"2",
"y":[
{"k": "3"},
{"i": "5"},
{"z": "4"},
{"p": null}
]
},
{
"a":null,
"x":"2"
}
]
Current checking function not working
//Checking passes in JSON array
checkData(dataSet) {
dataSet.forEach(function(obj) {
console.log("checking data");
if(!obj || obj === null){
return "";
}
else{
return obj;
}
});
}
This is a function that will recursively test/replace every property in a JSON hierarchy:
function process(obj) {
for (var i in obj) {
var child = obj[i];
if (child === null)
obj[i] = "";
else if (typeof(child)=="object")
process(child);
}
}
// try it out with your sample data
var data = [
{
"a":"1",
"x":null,
"y":[
{"k": "3"},
{"i": "5"}
]
},
{
"a":"1",
"x":"2",
"y":[
{"k": "3"},
{"i": "5"},
{"z": "4"},
{"p": null}
]
},
{
"a":null,
"x":"2"
}
];
process(data);
console.log(data);
An alternative method:
const newData = JSON.parse(JSON.stringify(testData, (key, value) =>
value === null || value === undefined
? '' // return empty string for null or undefined
: value // return everything else unchanged
));
Here's a function that recursively modifies the object or array passed to it:
// helper function to loop over array elements OR object properties
function iterator(cb, obj) {
if (Array.isArray(obj))
obj.forEach(cb);
else
Object.keys(obj).forEach(function(k) { cb(obj[k], k, obj); });
}
function replaceNulls(obj) {
iterator(function(v, k, o) {
if (v == null)
o[k] = "";
else if (typeof v === "object")
replaceNulls(v);
}, obj);
}
var input = [
{
"a":"1",
"x":null,
"y":[
{"k": "3"},
{"i": "5"},
null
]
},
null,
{
"a":"1",
"x":"2",
"y":[
{"k": "3"},
{"i": "5"},
{"z": "4"},
{"p": null}
]
},
{
"a":null,
"x":"2"
}
];
replaceNulls(input);
console.log(input);
Note that testing for null using == will also match undefined values. If you wanted to test for null but not undefined just use === instead.

AngularJS: Remove duplicate objects and reorder an array by value

I am using a json, this is the structure:
{ "variants": [
{ "capacity":"A", "color":"1" },
{ "capacity":"A", "color":"2" },
{ "capacity":"B", "color":"3" }
]};
Using angular.forEach or another method, I would like to display data no repeated, reordered it and related it by "capacity", something like this (a new array):
$scope.newArray = [
{ "capacity":"A", "color1":"1", "color2":"2" },
{ "capacity":"B", "color_1":"3" }
];
It is possible an angular way or simply javascript, I need help!
a = { 'variants': [
{'capacity': 'A','color': '1'},
{'capacity': 'A','color': '2'},
{'capacity': 'B','color': '3'},
]};
b = a.variants
c = b.reduce(function (prev, crt) {
prev[crt.capacity] = (prev[crt.capacity] || [
]).concat(crt.color)
return prev;
}, {})
// c is now {"A": ["1","2"], "B": ["3"]}
d = []
for (var name in c) {
if (c.hasOwnProperty(name)) {
f = {
'capacity': name
}
c[name].forEach(function (e) {
f['color' + e] = e;
})
// f is {"capacity": "A", "color1": "1","color2": "2"}
// and then {"capacity": "B", "color3": "3"}
d = d.concat(f)
}
}
// d is [{"capacity": "A", "color1": "1","color2": "2"},
// {"capacity": "B", "color3": "3"}]

Categories