I'd like to convert this object that I receive from server to a JSON file so that I can use it in d3.js chart:
data = {
"dog ":"5",
"cat ":"4",
"fish ":"12",
}
The output should be:
{
"name" : "animal",
"children" : [
{"name":"dog", "value": 5},
{"name":"cat", "value": 4},
{"name":"fish", "value": 10}
]
}
What I came up with is:
var jsonText = [] ;
for ( key in data) {
jsonText.push({name : key.trim(), value : parseInt(data[key])});
}
But when I try to print out the object, I receive:
[object Object],[object Object],[object Object]
In addition to that I have no clue how to add other attributes to the JSON file. So appreciate your hints.
You can use Object.keys(data) and loop through the key to get the desired object structure.
var data = {
"dog ":"5",
"cat ":"4",
"fish ":"12",
};
var res = {
name: "animal",
children: []
};
Object.keys(data).forEach((key)=>{
res.children.push(
{name:key.trim(), value: parseInt(data[key])}
);
});
console.log(res);
You're almost there (the array is formatted correctly), but you need the resulting array to be the value of the children property of the object. It would also be a bit easier to use Object.entries and map, which tranforms an array into another array based on the same elements:
const data = {
"dog ":"5",
"cat ":"4",
"fish ":"12",
};
const children = Object.entries(data)
.map(([name, value]) => ({ name: name.trim(), value: Number(value) }));
const output = { name: 'animal', children };
console.log(output);
Assuming you're manually adding a key like animal this should work and the values should be ints.
var data = {
"dog ":"5",
"cat ":"4",
"fish ":"12",
}
var children = Object.keys(data).map((key) => {
return {
name: key.trim(),
value: parseInt(data[key])
}
})
let result = JSON.stringify({
name: 'animal',
children
})
console.log(result);
That will return
{"name":"animal","children":[{"name":"dog ","value":5},{"name":"cat ","value":4},{"name":"fish ","value":12}]}
Try - console.log(JSON.stringify(jsonText))
Create an object with children key and push value to it
let data = {
"dog ": "5",
"cat ": "4",
"fish ": "12",
}
let newObj = {
"name": "animal",
"children": []
}
for (let keys in data) {
newObj.children.push({
name: keys.trim(),
value: parseInt(data[keys], 10)
});
}
console.log(newObj)
You could do something like this
const data = {
"dog ":"5",
"cat ":"4",
"fish ":"12",
}
Object.keys(data).reduce((obj, animal) => ({
...obj,
children: [
...obj.children,
{
name: animal,
value: data[animal]
}
]
}), {name: "animal", children: []})
console.log(JSON.stringify(obj))
This is a cleaner way to get the desired results in my opinion
You can just iterate over the data object using for..in and push prop: value pair objects into you children array:
const data = {
"dog ": "5",
"cat ": "4",
"fish ": "12",
}
let obj = {
name: "animal",
children: []
}
for (prop in data) {
let animal = {}
animal[prop.trim()] = Number(data[prop])
obj.children.push(animal)
}
console.log(JSON.stringify(obj))
Related
I have the json like follow example, i would like to convert this json map to array for to be able to loop on it.
I use the Object.keys method but I don't know how to have a key => value format for the whole json.
I need to get the keys to make a table I know there is the pipe keyvalue but it's not what I need. or maybe I use it wrong
example json
{
"pays": "UK"
"test": [
[
"123456", // here i want key id
"blabla", // here i want key name
"lorem ipsum" // here i want key type
],
[
"654321",
"ipsum",
"blabla"
]
]
}
components.ts
get() {
this.myService.getUrl().subscribe(data => {
this.myArray = Object.keys(data).map((key) => {
return {
id: key,
name: data[key]
}
}):
}
Please try this
var input: any = {
"pays": "UK",
"test": [
[
"123456", // here i want key id
"blabla", // here i want key name
"lorem ipsum" // here i want key type
],
[
"654321",
"ipsum",
"blabla"
]
]
}
input .test = input.test.map((item: any) => {
return {
id: item[0],
name : item[1],
type : item[2]
}
})
This is one possible solution to transform array of strings into array of JSONs:
let input = {
pays: "UK",
test: [
[
"123456",
"blabla",
"lorem ipsum"
],
[
"654321",
"ipsum",
"blabla"
]
]
};
let result = {};
result.pays = input.pays;
result.test = [];
for (let i = 0; i < input.test.length; i++){
let testEl = input.test[i];
let resultObj = {};
resultObj.id = testEl[0];
resultObj.name = testEl[1];
resultObj.type = testEl[2];
result.test.push(resultObj);
}
console.log(result)
Given the following object, how can I loop through this object inorder to obtain both keys and values but only for the following keys:
"myName": "Demo"
"active": "Y"
"myCode": "123456789"
"myType": 1
let a = {
"values": {
"myName": "Demo",
"active": "Y",
"myCode": "123456789",
"myType": 1,
"myGroups": [
{
"myGroupName": "Group 1",
"myTypes": [
{
"myTypeName": "323232",
"myTypeId": "1"
}
]
},
{
"myGroupName": "Group 2",
"myTypes": [
{
"myTypeName": "523232",
"myTypeId": "2"
}
]
}
]
}
}
I have tried:
for (const [key, value] of Object.entries(a.values)) {
console.log(`${key}: ${value}`);
For}
but this will return all keys with their values.
You can use a dictionary (array) to contain the keys you want to extract the properties for, and then reduce over the values with Object.entries to produce a new object matching only those entries included in the dictionary.
let a = {
"values": {
"myName": "Demo",
"active": "Y",
"myCode": "123456789",
"myType": 1,
"myGroups": [{
"myGroupName": "Group 1",
"myTypes": [{
"myTypeName": "323232",
"myTypeId": "1"
}]
},
{
"myGroupName": "Group 2",
"myTypes": [{
"myTypeName": "523232",
"myTypeId": "2"
}]
}
]
}
}
const arr = [ 'myName', 'active', 'myCode', 'myType' ];
const out = Object.entries(a.values).reduce((acc, [key, value]) => {
if (arr.includes(key)) acc[key] = value;
return acc;
}, {});
console.log(out);
The best answer would be to set up an array of the desired keys and then iterate over that array instead of an array of the original object's entries. This is how you would achieve that:
let a = {
values: {
myName: "Demo",
active: "Y",
myCode: "123456789",
myType: 1,
myGroups: [{
myGroupName: "Group 1",
myTypes: [{
myTypeName: "323232",
myTypeId: "1"
}]
}, {
myGroupName: "Group 2",
myTypes: [{
myTypeName: "523232",
myTypeId: "2"
}]
}]
}
};
const keys = ['myName', 'active', 'myCode', 'myType'];
const cherryPick = (obj, keys) => keys.reduce((a,c) => (a[c] = obj[c], a), {});
console.log(cherryPick(a.values, keys));
The above example will work for many provided keys. If a key does not exist in the supplied object, its value will be undefined. If you want to only keep properties which have values, simply add an optional filter to the cherryPick() function, like this:
let test = {
a: 1,
b: 2
};
const keys = ['a', 'b', 'c'];
const cherryPick = (obj, keys, filter = 0) => keys.filter(key => filter ? obj[key] : 1).reduce((acc,key) => (acc[key] = obj[key], acc), {});
console.log('STORE undefined :: cherryPick(test, keys)', cherryPick(test, keys));
console.log('FILTER undefined :: cherryPick(test, keys, 1)', cherryPick(test, keys, true));
/* Ignore this */ .as-console-wrapper { min-height: 100%; }
I have an object
var students = { 0: "Ann_L", 1: "Bob_P", 2: "Cat_C" }
How can I get an array from the object with its key and value?
var array = [
{ "Id": 0, "Value": "Ann_L", "Name": "Ann L" },
{ "Id": 1, "Value": "Bob_P", "Name": "Bob P" },
{ "Id": 2, "Value": "Cat_C", "Name": "Cat C" }
]
I have the values of the object but not the keys for "Id"
var array = Object.entries(students).map(([_, student ]) =>
({
Name: student.replace(/_/g, " "),
Id: ?,
Value: student
})
The key is the first element in the entries array
var array = Object.entries(students).map(([key, student ]) =>
({
Name: student.replace(/_/g, " "),
Id: key,
Value: student
})
You could assign the object to an array and map the objects.
var students = { 0: "Ann_L", 1: "Bob_P", 2: "Cat_C" },
array = Object
.assign([], students)
.map((Value, Id) => ({ Id, Value, Name: Value.replace(/_/g, ' ') }));
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Object.entries return [key, value] so in your code _ is key
You can use Object.entries and map and replace
var students = { 0: "Ann_L", 1: "Bob_P", 2: "Cat_C" }
let op = Object.entries(students).map(([Id,value]) => {
return {
Id,
value,
name: value.replace(/_/g, ' ')
}
})
console.log(op)
An alternative solution: you can use Object.keys, and iterate through the students object using the keys.
const students = { 0: "Ann_L", 1: "Bob_P", 2: "Cat_C" }
const res = Object.keys(students).map((element, index) => {
return {
Id: element,
Value: students[index],
Name: students[index].replace(/_/g, " "),
}
})
console.log(res)
This question already has answers here:
Convert Array to Object
(46 answers)
Closed 5 years ago.
I know this has been asked before, but every solution I found isn't doing it the way I need it.
The Array
[ {key: "Title", value: "Default Text"}, {key: "Title2", value: "Default Text2"} ]
Object I Need
{
"Title": "Default Text",
"Title2": "Default Text2"
}
Everything I try seems to return this which is wrong:
{ {key: "Title", value: "Default Text"}, {key: "Title2", value: "Default Text2"} }
I've tried most things I found here on SO.. the last one I've tried that is formatting it wrong is:
let obj = Object.assign({}, arrayHere);
What I want:
What I keep getting, but is wrong:
Use Array.prototype.reduce() function:
var arr = [ {key: "Title", value: "Default Text"}, {key: "Title2", value: "Default Text2"} ],
result = arr.reduce((r,o) => {r[o.key] = o.value; return r; }, {});
console.log(result);
You could assign the single created objects with Array#map and Object.assign
var array = [{ key: "Title", value: "Default Text" }, { key: "Title2", value: "Default Text2" }];
object = Object.assign({}, ...array.map(o => ({ [o.key]: o.value })));
console.log(object);
const a = [ {key: "Title", value: "Default Text"}, {key: "Title2", value: "Default Text2"} ];
function convertArr(arr) {
const res = {};
a.forEach((item) =>
res[item.key] = item.value;
})
return res;
}
convertArr(a);
Using Array.prototype.map(),
var Object = [ {key: "Title", value: "Default Text"}, {key: "Title2", value: "Default Text2"} ];
var result = Object.map(function(obj) {
var rObj = {};
rObj[obj.key] = obj.value;
return rObj; });
I have a JS data structure which comes from JSON like this:
[
{
"eid": "T1",
"name": "Topic1",
"children": [
{
"eId": "T1.1",
"name": "subtopic1",
"children": []
},
{
"eId": "T1.2",
"name": "subtopic2"
}
]
},
{
"eId": "T2",
"name": "Topic1",
"children": []
}
]
I need to iterate this and construct another structure that looks like:
[
{
"id": "T1",
"text": "Topic1",
"children": [
{
"id": "T1.1",
"text": "subtopic1",
"children": []
},
{
"id": "T1.2",
"text": "subtopic2"
}
]
},
{
"id": "T2",
"text": "Topic1",
"children": []
}
]
My code is here
// topics = the first strucutre
var treeData=[];
for(var i=0,len=topics.length;i<len;++i)
{
var topicElements=topics[i];
var subNodes=[];
var nodes={};
nodes['id']=topicElements.eId;
nodes['text']=topicElements.name;
for (var j =0;j<topicElements.children.length;++j)
{
nodesChildren = topicElements.children;
position = subNodes.length;
subNodes[position] = new Object();
subNodes[position]['id']=nodesChildren[j].eId;
subNodes[position]['text']=nodesChildren[j].name;
}
nodes['children']=subNodes;
treeData.push(nodes);
}
It works for one level but if I have to traverse children of T1.1 then it won't work. Can you suggest me a recursive way to do it?
Something like this maybe:
function redefineData(data) {
var outData = [];
for (var i = 0; i < data.length; i++) {
var obj = { id: data[i].eid, text: data[i].name };
if (data[i].children && data[i].children.length) {
obj.children = redefineData(data[i].children);
}
outData.push(obj);
}
return outData;
}
var treeData = redefineData(topics);
Here's a generic version in ES6 that I think is a bit simpler:
const renameKey = (oldName, newName) => (xs) =>
xs .map (({[oldName]: old, children, ...rest}) => ({
[newName]: old,
...rest,
...(children ? {children: renameKey (oldName, newName) (children)} : {})
}))
const fixId = renameKey ('eId', 'id')
const data = [{eId: "T1", name: "Topic1", children: [{eId: "T1.1", name: "subtopic1", children: []}, {eId: "T1.2", name: "subtopic2"}]}, {eId: "T2", name: "Topic1", children: []}]
const treeData = fixId (data)
console .log (treeData)
If you don't mind adding an empty children array to those that don't have one, you can simplify a bit:
const renameKey = (oldName, newName) => (xs) =>
xs .map (({[oldName]: old, children, ...rest}) => ({
[newName]: old,
...rest,
children: renameKey (oldName, newName) (children || [])
}))
If the sample data didn't have a typo, and you actually need to change both eId and eid to id, you can call it twice, once with each spelling. But if you want to entirely ignore case, then this would require a different technique (...and also possibly lead to problems if you had two different keys that are case-insensitively the same.)