As you asked, here's how to do it:
- Mapping the array to an object
- Converting the object to JSON
let array = [{
Field: 'Key',
Value: '7'
},
{
Field: 'City',
Value: 'Some City'
},
{
Field: 'Description',
Value: 'Some Description'
}
];
// #1 Mapping the array to an object...
let obj = {};
array.forEach(item => obj[item.Field] = item.Value);
// #2 Converting the object to JSON...
let json = JSON.stringify(obj);
console.log(json);
Bonus (ES6 + reduce):
const obj = array.reduce((acc, { Field, Value }) => ({ ...acc, [Field]: Value }), {});
Answer from Maxime Gélinas on Stack OverflowAs you asked, here's how to do it:
- Mapping the array to an object
- Converting the object to JSON
let array = [{
Field: 'Key',
Value: '7'
},
{
Field: 'City',
Value: 'Some City'
},
{
Field: 'Description',
Value: 'Some Description'
}
];
// #1 Mapping the array to an object...
let obj = {};
array.forEach(item => obj[item.Field] = item.Value);
// #2 Converting the object to JSON...
let json = JSON.stringify(obj);
console.log(json);
Bonus (ES6 + reduce):
const obj = array.reduce((acc, { Field, Value }) => ({ ...acc, [Field]: Value }), {});
you can try the below approach . I have used spread operator(ES6) and Object.assign to create the object ,then converted it into json string.
let SampleData = [
{ Field: 'Key', Value: '7'},
{ Field: 'City', Value: 'Some City'},
{ Field: 'Description', Value: 'Some Description'}
];
let obj = Object.assign(...SampleData.map( x => Object.values(x)).map(y => ({[y[0]]: y[1]})));
console.log(obj);
//{ Key: "7", City: "Some City", Description: "Some Description" }
console.log(JSON.stringify(obj));
TypeScript - how to parse JSON array into array of custom objects
Convert JSON file to Typescript Array of Objects
The interface has an iD field and the json has a date field. They need to be the same types. You also might need to use JSON.parse(stringValue) depending on how you are getting the JSON data.
More on reddit.comHow to convert JSON object to an Typescript array? - Stack Overflow
TypeScript casting json array - Stack Overflow
I am reading in a JSON file and attempting to convert them to an array of objects. I get a syntax error on the component file.
This is the component code:
import * as blogs from '../story/stories.json';
import { IStory } from '../models/story';
@Component({
selector: 'app-story',
templateUrl: './story.component.html',
styleUrls: ['./story.component.scss']
})
export class StoryComponent implements OnInit {
stories: IStory[] ;
constructor() { }
ngOnInit() {
this.stories = blogs; <-- syntax error on this line
}this is the story.ts file:
export interface IStory {
id: number;
author: string;
title: string;
pictureUrl: string;
body: string;
}This is the json file, stories.json
[
{"date":3,"author":"AVC", "pictureUrl":"Scorching", "title":"Scorching", "body":"Scorching"},
{"date":4,"author":"ADF", "pictureUrl":"Scorching", "title":"Scorching", "body":"Scorching"}
]The interface has an iD field and the json has a date field. They need to be the same types. You also might need to use JSON.parse(stringValue) depending on how you are getting the JSON data.
It might be simpler to just use the http client to get the json. Pass it the type and you should get proper data objects back.
To convert any JSON to array, use the below code:
const usersJson: any[] = Array.of(res.json());
That's correct, your response is an object with fields:
{
"page": 1,
"results": [ ... ]
}
So you in fact want to iterate the results field only:
this.data = res.json()['results'];
... or even easier:
this.data = res.json().results;
If the response is what you included then it's simple:
JSON.parse(data.text()).forEach(item => {
console.log(item.name);
});
As your body is an array of objects of this interface:
interface ObjectInResponseArray {
name: string;
}
First off, you're mixing up JSON and objects. JSON is a text format for transferring data. Once you parse it (JSON.parse) you've got an object or an array, depending on the contents of the JSON.
var json = "{\"key\": \"value\" }";
var object = JSON.parse(json);
json = "[1, 2, \"three\"]";
var array = JSON.parse(json);
Next, it looks like you already have an object. If you do JSON.stringify, you're converting an object into a string. So you can access your data object directly. No need to convert one way or the other.
console.log(data._body[0]);
Are you familiar with for loops? They're the most common way of iterating through an array in JavaScript (and most languages, actually). For example:
var objs = [
{
name: 'Bugs'
},
{
name: 'Bunny'
}
];
for (var i = 0; i < objs.length; i++) {
var obj = objs[i];
console.log(obj.name);
}
Given all of that, you should be able to iterate over your data._body array and access the name property on each element.
Since your question is a bit unclear, it's possible you'll need to iterate over the parsed contents of data.text().
var objs = JSON.parse(data.text());
// Use a simple loop like above