I am trying to set table values from webservice response.
Iam getting my web service response like this.but if he response is like this means it is not getting set there.This response can be dynamic.
0:{name: "image.png", base64: "iVBORw"}
1:{name: "download.png", base64: "iVBO"}
2:{name: "test-animation.gif", base64: "R0lGODlhLAEs"}
How can i change it to??
[["image.png", "iVBORw"],["download.png", "iVBO"],[test-animation.gif", "R0lGODlhLAEs"]]
here it is what iam trying
$.cordys.ajax({
method: "somewebservice",
namespace: "Package",
parameters: {
emailid:mailidvalue
},
dataType: '* json',
success: function (result) {
output=result;
bodycontent=output["data"]["body"];
var attachvalue=result.data.tuple;
$('#attachmenttable').DataTable( {
"data": attachvalue,
columns: [
{ title: "File Name" },
{ title: "Base64" }
]
} );
},
error: function(err){
console.log(err);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
I see a 1-1 mapping between what you are given and what you desire, therefore use Array.prototype.map() or $.map.
var given = {
0: {
name: "image.png",
base64: "iVBORw"
},
1: {
name: "download.png",
base64: "iVBO"
},
2: {
name: "test-animation.gif",
base64: "R0lGODlhLAEs"
}
};
var desired = Object.keys(given).map(function(key) {
return [ given[key].name, given[key].base64 ];
});
console.log(desired);
var given = {
0: {
name: "image.png",
base64: "iVBORw"
},
1: {
name: "download.png",
base64: "iVBO"
},
2: {
name: "test-animation.gif",
base64: "R0lGODlhLAEs"
}
};
var desired = $.map(given, function (value, key) {
return [[ given[key].name, given[key].base64 ]];
});
console.log(desired);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Related
I have data like this:
const currentData = {
id: "u76u76h",
type: "cardA",
name: "Section 1",
thumbnail: {
src: "",
alt: "",
},
data: {
avatar: {
dataType: "image",
src: "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEBXgFy56y56y56",
alt: "avatar"
},
album: [
{
dataType: "image",
src: "https://firebasestorage.googleapis.com/album_image1.png",
alt: "album_image1"
},
{
dataType: "image",
src: "https://firebasestorage.googleapis.com/album_image2.png",
alt: "album_image2"
}
],
cards: [
{
icon: {
dataType: "image",
src: "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEBXgF",
alt: "card_image1"
},
title: "新規事業企画担当",
description: [
"企画書だけでは、「新しいビジネスの良さを理解してもらう事」が難しい!",
"アイディアを実際に使ってもらって実感してもらいたい!"
]
}
]
}
};
I want to extract all the base64 urls (none https) and upload to cloud storage, and after uploaded the storage I want to update the uploaded urls to the data object above before saving the data object to the database. But the problem is the data structure is complicated and can be 2 or 3 or more in nested level. I am scratching my head to find a solution. Please help me!
You can use recursion to view the whole object. Be careful if the object contains circular references.
And remove isBase64Fake function. Use isBase64 instead. I've added isBase64Fake only to check your object.
function extractBase64(data) {
const result = [];
Object.keys(data).forEach((key) => {
if (typeof data[key] === 'string') {
isBase64Fake(data[key]) && result.push({
data,
key,
value: data[key]
});
} else if (typeof data[key] === 'object') {
result.push(...extractBase64(data[key]));
}
});
return result;
}
function uploadSomewhere(dataToUpload) {
console.log('uploading...');
setTimeout(() => {
dataToUpload.forEach((item) => {
item.data[item.key] = 'QWERTY';
});
}, 1000);
}
function isBase64Fake(str) {
return /^data:/.test(str);
}
function isBase64(str) {
if (!str) {
return false;
}
try {
window.atob(base64);
result = true;
} catch (e) {
result = false;
}
}
const currentData = {
id: "u76u76h",
type: "cardA",
name: "Section 1",
thumbnail: {
src: "",
alt: "",
},
data: {
avatar: {
dataType: "image",
src: "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEBXgFy56y56y56",
alt: "avatar"
},
album: [{
dataType: "image",
src: "https://firebasestorage.googleapis.com/album_image1.png",
alt: "album_image1"
},
{
dataType: "image",
src: "https://firebasestorage.googleapis.com/album_image2.png",
alt: "album_image2"
}
],
cards: [{
icon: {
dataType: "image",
src: "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEBXgF",
alt: "card_image1"
},
title: "新規事業企画担当",
description: [
"企画書だけでは、「新しいビジネスの良さを理解してもらう事」が難しい!",
"アイディアを実際に使ってもらって実感してもらいたい!"
]
}]
}
};
const dataToUpload = extractBase64(currentData);
console.log(dataToUpload);
uploadSomewhere(dataToUpload);
setTimeout(() => console.log(currentData), 2000);
I have this JSON generated from external (Reviews-io) script:
https://widget.reviews.co.uk/rich-snippet/dist.js
richSnippet({
store: "www.storedigital.local",
sku:"6647;6647_5;6647_4;6647_3;6647_11;6647_10;6647_2;6647_1;6647_9;6647_8;6647_7;6647_6",
data:{
"url": "store.stg.gsd.local/1/silla-replica-eames.html",
"description": ``,
"mpn": "6647",
"offers" :[{
"#type":"Offer",
"availability": "http://schema.org/InStock",
"price": "559",
"priceCurrency": "MXN",
"url": "https://store.stg.gsd.localx/1/silla-replica-eames.html",
"priceValidUntil": "2022-05-26",
}],
"brand": {
"#type": "Brand",
"name": "Not Available",
}
}
})
I need to get all the string of numbers in "sku", and then put them in another variable as same format (6647; 6647_1; 6647_2)
I try to get the numbers using this JS but doesn't works
var skucollection = JSON.parse(richSnippet, function (key, value) {
if (key == "sku") {
return new Sku(value);
} else {
return value;
}
});
Can you help me check what I am doing wrong, to get this sku's value string, please?
JSON.parse is not too much? ,handle it as it is internally (a JSON indeed)
var richSnippet = {
store: 'www.storedigital.local',
sku: '6647;6647_5;6647_4;6647_3;6647_11;6647_10;6647_2;6647_1;6647_9;6647_8;6647_7;6647_6',
algomas: [],
data: {
url: 'store.stg.gsd.local/1/silla-replica-eames.html',
description: ``,
mpn: '6647',
offers: [
{
'#type': 'Offer',
availability: 'http://schema.org/InStock',
price: '559',
priceCurrency: 'MXN',
url: 'https://store.stg.gsd.localx/1/silla-replica-eames.html',
priceValidUntil: '2022-05-26',
},
],
brand: {
'#type': 'Brand',
name: 'Not Available',
},
},
};
var test;
Object.keys(richSnippet).forEach((key) => {
if (key == 'sku') {
test = richSnippet[key];
}
});
console.log('test', test);
Imagine you have this data structure:
const data = {
posts: [{
id: 1,
title: "Post 1"
slug: "post-1"
}, {
id: 2,
title: "Post 2"
slug: "post-2"
}],
comments: [{
id: 1,
postId: "post-1",
text: "Comment 1 for Post 1"
}, {
id: 2,
postId: "post-1",
text: "Comment 2 for Post 1"
}, {
id: 3,
postId: "post-2",
text: "Comment 1 for Post 2"
}]
}
An you have the following route /posts/[postId[/[commentId]
so the Next.js structure folder is: posts/[postId]/[commented].js
Then you need to generate the static paths for this routes.
I'm coded the following:
export async function getStaticPaths() {
const { posts, comments } = data
const paths = posts.map((post) => {
return comments
.filter((comment) => comment.postId === post.slug)
.map((comment) => {
return {
params: {
postId: post.slug,
commentId: comment.id
}
}
})
})
}
But it's not working. The throwed error was:
Error: Additional keys were returned from `getStaticPaths` in page "/clases/[courseId]/[lessonId]". URL Parameters intended for this dynamic route must be nested under the `params` key, i.e.:
return { params: { postId: ..., commentId: ... } }
Keys that need to be moved: 0, 1.
How I can "map" or "loop" the data to a proper returned format?
Thanks in advance!
The problem seems to be that your returning this from getStaticPaths data with a wrong shape:
[
[ { params: {} }, { params: {} } ],
[ { params: {} } ]
]
The correct shape is:
[
{ params: {} },
{ params: {} },
{ params: {} }
]
Just tried this and it works.
export async function getStaticPaths() {
const paths = data.comments.map((comment) => {
return {
params: {
postId: comment.postId,
commentId: comment.id
}
}
});
console.log(paths);
return {
paths,
fallback: false
}
};
It generates 3 urls:
/posts/post-1/1
/posts/post-1/2
/posts/post-2/3
Is that what you need?
Like mention #Aaron the problem is for double array of filter y el map.
return {
paths: [
{ params: { id: '1' } },
{ params: { id: '2' } }
],
fallback: ...
}
Doc 📚 ➡ https://nextjs.org/docs/basic-features/data-fetching#the-paths-key-required
I have something like this :
let user = [
{
name: "step-one",
values: {companyName: "Name", address: "company address"}
},
{
name: "step-two",
values: {name: "User", mobile: 0123}
},
{
name: "step-three",
values: [
{file: "companyLogo", values: {active: true, fileName: "some name"}},
{file: "avatar", values: {active: true, fileName: "file name"}}
]
}
]
I want to get only values and put them into a new object. Thus, something like :
let wantedResult = {
companyName: "Name",
address: "company address",
name: "User",
mobile: 0123,
files: [
{file: "companyLogo", values: {active: false, fileName: "some name"}},
{file: "avatar", values: {active: false, fileName: "file name"}}
]
};
Any advice how I can do that?
You can try this!
let user = [{
name: "step-one",
values: {
companyName: "Name",
address: "company address"
}
}, {
name: "step-two",
values: {
name: "User",
mobile: 0123
}
}, {
name: "step-three",
values: [{
file: "companyLogo",
values: {
active: true,
fileName: "some name"
}
}, {
file: "avatar",
values: {
active: true,
fileName: "file name"
}
}]
}]
var wantedResult = Object.assign({}, user[0].values, user[1].values, {files: user[2].values})
console.log(wantedResult)
It is a bit hacky because of the files array, but i would do it like that:
var wantedResult = user.reduce((result, step) => {
var values = Array.isArray(step.values) ? { files: step.values } : step.values;
return Object.assign({}, result, values)
}, {});
Of course it'll work only for that kind of structure you provided. If you have more objects that have an array in the 'values' property, you'll need to rethink the approach.
Step 3 is inconsistent with the others. If possible, make it consistent to have: values: files: [ { file1_data }, { file2_data } ].
After fixing the inconsistency, you can iterate through each of the steps and add the new properties to the result.
let wantedResult = user.reduce(function(result, spec) {
Object.keys(spec.values).forEach(function(key) {
result[key] = spec.values[key];
});
return result;
}, {});
If not possible to change step 3, you can make it a bit less clean:
let wantedResult = user.reduce(function(result, spec) {
if (spec.name === "step-three") {
result.files = spec.values;
}
else {
Object.keys(spec.values).forEach(function(key) {
result[key] = spec.values[key];
});
}
return result;
}, {});
I'm new to AngularJS and so far haven't had any problems until this one...
I am trying to display json data returned for my REST service call without any luck. I can hard-code in a data array into my controller script file and that will be displayed on my web page just fine however when trying to display my json data I'm not having any luck.
This is what I currently have coded...
Web page-
<div ng-controller="ExceptionLogDataController">
<div ui-grid="gridOptions" class="vertexGrid"></div>
</div>
ExceptionLogDataController-
$scope.vertexData = [];
$scope.gridOptions = {
enableSorting: true,
data: "vertexData",
columnDefs: [
{ name: 'Data Id', field: 'DataId' },
{ name: 'Source Date Time', field: 'SourceDateTime' },
{ name: 'Message Text', field: 'MessageText' },
{ name: 'IsDirty', field: 'IsDirty' }
// { name: 'FileName', field: 'FileName' },
// { name: 'GenJIRATicket', field: 'GenJIRATicket' },
// { name: 'MessageCount', field: 'MessageCount' },
// { name: 'MachineName', field: 'MachineName' },
// { name: 'AppDomainName', field: 'AppDomainName' },
// { name: 'ProcessName', field: 'ProcessName' },
// { name: 'StackTrace', field: 'StackTrace' }
],
};
//$scope.vertexData = [
// {
// "First Name": "John",
// "Last Name": "Smith",
// },
// {
// "First Name": "Jane",
// "Last Name": "Doe",
// }
//];
$scope.load = function () {
ExceptionLogDataFactory()
.then(function (response) {
$scope.vertexData = JSON.parse(response.data);
});
}
$scope.load();
}
ExceptionLogDataController.$inject = ['$scope', 'ExceptionLogDataFactory'];
ExceptionLogDataFactory-
var ExceptionLogDataFactory = function ($http, $q, SessionService) {
return function () {
var result = $q.defer();
$http({
method: 'GET',
url: SessionService.apiUrl + '/api/ExceptionLogData',
headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + SessionService.getToken() }
})
.success(function (response) {
result.resolve(response);
})
.error(function (response) {
result.reject(response);
});
return result.promise;
}
}
ExceptionLogDataFactory.$inject = ['$http', '$q', 'SessionService'];
I've verified that my REST call is returning JSON data through Postman so the problem lies with my front end code.
Making progress...
I'm getting my json object successfully returned and am trying to display it with the following...
$scope.data = [];
$scope.gridOptions = {
enableSorting: true,
data: 'data',
};
ExceptionLogDataService() //Call to Service that returns json object
.then(function (data) {
$scope.data = data;
$scope.gridOptions.data = $scope.data;
console.log($scope.data);
}
And this is the json object that is being returned via console.log call...
Object { DataId: 1074, SourceDateTime: "2016-01-19T13:29:01.2512456-05:00", MessageText: "There is an error in XML document (…", IsDirty: false, StatusList: Object, FileName: "D:\ProdMonitorSiteDev\ErrorFiles\…", GenJIRATicket: false, MessageCount: 1, MachineName: "VERTEXCUTIL01", AppDomainName: "", 2 more… }
This is the error that I am getting...
Error: newRawData.forEach is not a function
Well I figured it out!
I finally got my head out of the weeds and 'really' looked at the JSON object that was being returned from my service and noticed that the object was encapsulated with '{}' (curly braces) which is what was causing the newRawData.forEach error. So what I did was the following...
.then(function (data) {
$scope.data = "[" + JSON.stringify(data) + "]"; // 'Stringify my object and then encapsulate it with square brackets '[]' and then I could use JSON.parse to then parse the new string into a JSON object...
$scope.data = JSON.parse($scope.data);
// Worked like a champ!....
$scope.gridOptions.data = JSON.stringify($scope.data);
You don't need to parse the JSON.
$http.get(url)
.success(function (data) {
$scope.gridOptions.data = data;
}
This should work just fine for what you are doing.