I want to make Json attribute using const data
like this.
const title = 'NAME'
data = {title: 'This is title'}
console.log(JSON.stringify(data))
I want this result
=> {NAME: 'This is title'}
but this shown
=> {title: 'This is title'}
What should I do?
For dynamic key, you can use [variableName] notation.
So change title to [title]
const title = 'NAME'
data = {[title]: 'This is title'}
console.log(JSON.stringify(data))
Related
I'm having an issue rendering a Twig view and a JSON response, I need to call the twig view and pass it a new Json response with a variable as parameter. The output error is the following "Notice: Object of class Symfony\Component\HttpFoundation\Response could not be converted to int
"
Here is the code
$resultado = array('mes1_local' => $mes1_local, 'mes2_local' => $mes2_local, 'mes3_local' => $mes3_local, 'mes1_online' => $mes1_online, 'mes2_online' => $mes2_online, 'mes3_online' => $mes3_online, 'contador_pedido_local' => $contador_pedido_local, 'contador_pedido_online' => $contador_pedido_online, 'contador_total' => $contador_total, 'contador_usuarios' => $contador_usuarios);
return new JsonResponse($resultado, $this->render('others/adminlte.html.twig'));
Like #goto's answer, but it won't works, cause you need to use renderView instead of render:
return new JsonResponse([
'things' => $thingsArray,
'anotherVariable' => $simpleVariable,
'html' => $this->renderView('others/adminlte.html.twig', []/* template parameters goes here */),
]);
The Json Response signature is
__construct(mixed $data = null, int $status = 200, array $headers = array(), bool $json = false)
You are trying to give the twig to the status parameter.
You can avoid this silly error by using a good IDE
To give additional data to your response you could structure your array data returned
return new JsonResponse([
'someData' => $resultado,
'html' => $this->render('others/adminlte.html.twig')
);
I have a complicated data structure that I need to convert to JSON. The problem is that my field names and values are in an array.
For instance, I have the following (simplified from my code base):
let SampleData = [
{ Field: 'Key', Value: '7'},
{ Field: 'City', Value: 'Some City'},
{ Field: 'Description', Value: 'Some Description'}
];
Basically my data is an array where the first element is the database column name, and the second element is the data in the column. I am trying to get a JSON object that is:
{ Key: 7, City: 'Some City', Description: 'Some Description' }
My real code has the fields and data is structures within the object, so I cannot simply use an Object.create() or Object.assign() as far as I can get working.
I have tried looping through to build a simple string and then use the JSON.parse to break it apart, but this seems like a lot of overhead for something I would have thought would be simpler.
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 }), {});
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));
I had a similar requirement and here is how I achieved it.
var ranges: segmentRange[] = new Array(2);
ranges[0] = { minimumPercentage: 50, maximumPercentage: 60 };
ranges[1] = { minimumPercentage: 30, maximumPercentage: 40 };
const segmentRanges = { segmentRanges: ranges };
return JSON.stringify(segmentRanges);
Output:
{"segmentRanges":[{"minimumPercentage":50,"maximumPercentage":60},{"minimumPercentage":30,"maximumPercentage":40}]}
HTH,
i'm new to es6 and i have an array of objects like below:
checkProps = [ {symbol: rwerwe}, {side: Buy}, {status: Hey} ]
With a for loop i want to create a string like:
myurl = localhost:3000/symbol=rwerwe&side=Buy&status=Hey
For this i have to get access to the keys of each object and use concat for the string composition. I used Object.keys but it returns integers. I want something to return the symbol, side and status. How to do this?
Please try this:
var checkProps = [ {symbol: 'rwerwe'}, {side: 'Buy'}, {status: 'Hey'} ];
var urlStr = 'localhost:3000/';
var urlParams = [];
checkProps.forEach(function(o) {
var keys = Object.keys(o);
keys.map(function(key) {
urlParams.push(key + '=' + o[key])
});
});
urlStr += urlParams.join('&');
console.log(urlStr)
You need to loop over the array and apply Object.keys to the items.
const parameters = checkProps.map(item => Object.keys(item).map(key => key + "=" + item[key])[0])
.join("&");
const myUrl = `localhost:3000/${parameters}`;
It's a bit cleaner with ES2017 and Object.entries:
const parameters = checkProps.map(item => Object.entries(item)[0])
.map(parameter => parameter.join("="))
.join("&");
I am new to laravel and I am facing following problem
My problem
Problem i m facing is that whenever I submit the form after filling firstname lastname and phone, then everything going well except one thing that in my MYSQL database data is save as firstname: NULL lastname:NULL And phone:NULL instead of saving the data which i had enter.
I have a angularjs form in which is there fields like firstname lastname and phone.on submit it goes to submitContact() in controller:
submit.js:
var addnew = angular.module('addnew',[]);
// create angular controller
addnew.controller('addContactController',
function($scope,$location,$window,$http) {
// function to submit the form after all validation has occurred
$scope.submitContact = function() {
$scope.addnew = {firstname:'', lastname:'',phone:''};
$scope.addnew.firstname=$scope.firstname;
$scope.addnew.lastname=$scope.lastname;
$scope.addnew.phone=$scope.phone;
$http.get("http://localhost:8000/index.php/user/addnew",{"firstname": $scope.firstname, "phone": $scope.phone, "lastname": $scope.lastname})
.then(function mysuccess(response) {
$scope.mycard = response.data;
$scope.statuscode = response.status;
$scope.statustext = response.statustext;
$window.alert(JSON.stringify(response));
console.log(response.data);
});
};
});
http://localhost:8000/index.php/user/addnew this links to my laravel through routes.
my route.php:
Route::get('/user/addnew', 'usercontroller#store');
my usercontroller.php
public function store(Request $request)
{
//contacts::create(Request::all());
$user = new contacts;// contacts is my table name and my database is defined in .env file
$user->firstname = Input::get('firstname');
$user->lastname = Input::get('lastname');
$user->phone = Input::get('phone');
$user->save();
//I Used print_r to see that weather my submitted data is coming in $user or not:
print_r($user);
echo "saved";
}
my contact.php:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class contacts extends Model
{
protected $fillable =['firstname','lastname','phone'];
}
?>
Now, My problem
when i print_r $user then i got the error as my array is NOT catching my submitted data
print_r ($user) output in console window:
[fillable:protected] => Array
(
[0] => firstname
[1] => lastname
[2] => phone
)
[connection:protected] =>
[table:protected] =>
[primaryKey:protected] => id
[keyType:protected] => int
[perPage:protected] => 15
[incrementing] => 1
[timestamps] => 1
[attributes:protected] => Array
(
[firstname] =>
[lastname] =>
[phone] =>
[updated_at] => 2016-10-07 03:46:34
[created_at] => 2016-10-07 03:46:34
[id] => 38
)
[original:protected] => Array
(
[firstname] =>
[lastname] =>
[phone] =>
[updated_at] => 2016-10-07 03:46:34
[created_at] => 2016-10-07 03:46:34
[id] => 38
)
I want to know where I m making mistake and how can I correct that mistake.
Thanking you in anticipation.
Try this:
$user = new Contact();
Instead of this:
$user = new contacts;
Also, change class name to class Contact extends Model and a filename to a Contact.php.
Alternatively, since you're using $fillable you can create new row:
Contact::create($request->all());
https://laravel.com/docs/5.3/eloquent#mass-assignment
I think you should use POST instead of GET.
$http.post("http://localhost:8000/index.php/user/addnew",{"firstname": $scope.firstname, "phone": $scope.phone, "lastname": $scope.lastname})
.then(function mysuccess(response) {
$scope.mycard = response.data;
$scope.statuscode = response.status;
$scope.statustext = response.statustext;
$window.alert(JSON.stringify(response));
console.log(response.data);
});
And
Route::post('/user/addnew', 'usercontroller#store');
And I noticed that you are posting to /index.php/user/addnew
And your route is '/user/addnew'
'/index.php/user/addnew' and '/user/addnew' are different.
try posting to localhost:8000/user/addnew instead
To explain:
/user/addnew always refer to host:port/user/addnew
While user/addnew will just concatenate it to your current url
for example if you're currently at: localhost:8000/users/1
Clicking a link to user/addnew will bring you to localhost:8000/users/1/user/addnew while a link to /user/addnew will bring you to localhost:8000/user/addnew
EDIT:
Is this redundant?
$scope.addnew.firstname=$scope.firstname;
$scope.addnew.lastname=$scope.lastname;
$scope.addnew.phone=$scope.phone;
What you were sending is this:
{"firstname": $scope.firstname, "phone": $scope.phone, "lastname": $scope.lastname}
I think you can send this instead:
$scope.addnew
and again, you should use POST, not GET.
did you already update your http request to post? did you update the url?
Actually, I achived this by using $request->input('firstname'); $request->input('firstname'); $request->input('firstname');, since, it was JSON thats why. Else, If I had been using Laravel blade file then I could have done it by above solutions.
i have a json which is this:
var jsonData = new
{
total = totalPages,
page = page,
records = totalRecords,
rows = reservations.Select(x => new { x.ReservationId, x.Employee.Name,roomName = x.Room.Name, x.Date, x.StartTime, x.EndTime, x.Notes}).ToList()
.Select(x => new
{
id = x.ReservationId,
cell = new string[]
{
roomName,
x.Name,
x.Date.ToString().Split(' ')[0],
x.StartTime.ToString().Remove(5) +" - " +x.EndTime.ToString().Remove(5),
x.Notes,
String.Format("<input type=\"button\" value=\"DETAILS\" onclick=\"window.location.href='/Reservation/Details/{0}'\"/>   <input type=\"button\" value=\"EDIT\" onclick=\"window.location.href='/Reservation/Edit/{0}'\"/>   <input type=\"button\" value=\"DELETE\" onclick=\"window.location.href='/Reservation/Delete/{0}'\"/>", x.ReservationId),
}
}).ToArray(),
};
this json will be returned to a jqGrid. when i typed x.Room.Name in the first select statement, an error occured because a property with the same name already exists (i.e. x.Employee.Name).
so i tried "roomName=x.Room.Name" and i put roomName in the cell content.
however, when the json is returned to my jqGrid, the column, which supposedly contains the roomName, is empty. how could i show the values of x.Room.Name in other ways?
Since you have renamed the column to roomName make sure that on the client you have a corresponding column:
$('#grid').jqGrid({
colNames: [ 'roomName', 'Name', ..... other columns ],
colModel: [
{ name: 'roomName', index: 'roomName' },
{ name: 'Name', index: 'Name' },
.....
],
........
});