I have a object like this.
sliderArray:
[
"../assets/slides/1.jpg",
"../assets/slides/2.jpg",
]
Can I reformat it like this in Vue?
sliderArray2:
[
{url: require("../assets/slides/1.jpg")},
{url: require("../assets/slides/2.jpg")},
]
This is easy to do with a map, which applies the same function to every element of an array
let obj = { sliderArray: [
"../assets/slides/1.jpg",
"../assets/slides/2.jpg",
]
};
function formatArray(a) {
return a.map(x => { return { url: require(x) } });
}
obj.sliderArray = formatArray(obj.sliderArray);
Related
I have a JSON that contains a lot of data, here's an example of it:
{
"type":"doc",
"content":[
{
"type":"paragraph",
"content":[
{
"text":"this is a simple page, about a simple umbrella.",
"type":"text"
}
]
},
{
"type":"paragraph",
"content":[
{
"text":"you can use this text to find the umbrella page.",
"type":"text"
}
]
},
{
"type":"paragraph",
"content":[
{
"text":"do you like it?",
"type":"text"
}
]
}
}
I want to extract the value of text key, no matter where the key is located. I'm trying to go over the keys using Object.keys but it only returns the top-level keys:
for (let x of Object.keys(someJson)) {
console.log(x);
}
How can I find all the values of text in this JSON, no matter where in the JSON it is?
You can use JSON.stringify trick, you can intercept all keys from it
function find(obj: object, key: string) {
const ret: any[] = [];
JSON.stringify(obj, (_, nested) => {
if (nested && nested[key]) {
ret.push(nested[key]);
}
return nested;
});
return ret;
};
...
const o = {
key: '123',
a: {
key: 'hello',
b: [
{
c: {
key: 123,
},
},
],
},
};
it('123', () => {
console.log(JSON.stringify(find(o, 'key'))); // ["123","hello",123]
});
if you want for generic JSON just call this function and pass your object :
function printText(obj){
if(Array.isArray(obj)){
for(const o of obj){
printText(o);
}
}else if(typeof obj === "object"){
if (obj){
for(const o of Object.keys(obj)){
if(o==="text"){
console.log(obj.text);
}else{
printText(obj[o]);
}
}
}
}
}
I'm quite newbie in this sort of stuffs. I have much bigger JSON like this:
{ "X": {
"child1": {
"k1": [],
"k2": "12",
"k3": "abc"
},
"ver": {
"dev1": {
"key1": "0x0100"
},
"dev2": {
"key1": "0x0003",
"key2": "0x0300"
},
"dev3": {
"key1": "0x990",
"key3": "0x0400",
"key2": "0x0100"
}}}}
As I would need to use angular tree component I need to transform the format above to something like this:
{name:X, children: [{name: child1, children: [{name: k1, children: [{name: []}]}]....
My question is how to go through the whole json to make this transformation? It should be probably possible via recursion, but I have never tried it.
My try for recursion:
recursive(obj) {
if (obj instanceof String) {
return {name: obj};
} else if (obj instanceof Array) {
const arr = [];
obj.forEach(item => {
arr.push({name: item})
return arr;
});
} else {
Object.keys(item => {
return this.recursive(obj[item]);
});
}
}
You're close, but you need to make sure to return something from each case of the recursive function. Returning a value from a callback will not return it from the main function. Also, Object.keys just returns an array of keys; if you want to iterate over them, you have to do that separately. This would be my proposed solution:
recursive(name, obj) {
if (typeof obj === "string") {
return { name: name + ": " + obj };
} else if (obj instanceof Array) {
return { name: name, children: obj.map(item => this.recursive("", item)) };
} else {
return { name: name, children: Object.keys(obj).map(k => this.recursive(k, obj[k])) };
}
}
You can adjust the way the names are handled as desired.
I am trying to change in my Angular (TypeScript) project a JSON list received through a REST request.
The initial JSON looks like this:
[
{
"id":1,
"position":3,
"articleNumber":6
},
{
"id":2,
"position":2,
"articleNumber":7
}
]
I need it to become:
{
"data":[
{
"data":{
"id":1,
"position":3,
"articleNumber":6
}
},
{
"children":[
{
"data":{
"id":2,
"position":2,
"articleNumber":7
}
}
]
}
]
}
I managed to add the 'data' tag by creating a new object { data: } and then assign to data property the result of array.map.
const mapped = { data: array.map(item => ({ data: item }))};
As a result, i get this:
{
"data":[
{
"data":{
"id":1,
"position":3,
"articleNumber":6
}
},
{
"data":{
"id":2,
"position":2,
"articleNumber":7
}
}
]
}
How can I add the 'children' tag too, which may contain many 'data's?
Have a look on this logic:
let array = [ {
"id":1,
"position":3,
"articleNumber":6},{
"id":2,
"position":2,
"articleNumber":7}];
const mapped1 = { data: array[0]};
const mapped2 = { children: array.map((item, index) => ({ data: item }))} ;
const final = {data:[mapped1]};
final.data.push(mapped2);
console.log(final);
import { Response } from '#angular/http';
in your service: .map((item: Response) => item.json());
Now, in your controller(component.ts) use .subscribe(), you will get the object as it is in JSON.
I'm trying to get a simple value out of my json string. It seems to be harder than I thought. How can I reach for example the 'name' of the first ModuleAction object in the following JSON (the first array is called 'data'):
[
{
"ModuleController":{
"id":"3"
},
"ModuleActionModuleController":[
{
"id":"4",
"module_action_id":"1",
"module_controller_id":"3",
"ModuleAction":{
"id":"1",
"name":"Overzicht",
"action":"index"
}
},
{
"id":"5",
"module_action_id":"2",
"module_controller_id":"3",
"ModuleAction":{
"id":"2",
"name":"Detail",
"action":"view"
}
}
]
}
]
Here's my best attempt:
data[0].ModuleActionModuleController[0].id
But I've got the error:
add:93 Uncaught TypeError: Cannot read property '0' of undefined
at Object.success (add:93)
at j (jquery-2.1.0.min.js:2)
at Object.fireWith [as resolveWith] (jquery-2.1.0.min.js:2)
at x (jquery-2.1.0.min.js:4)
at XMLHttpRequest.<anonymous> (jquery-2.1.0.min.js:4)
Any idea what I'm doing wrong? :)
EDIT
Here's the ajax function that returns the data JSON string:
$(function() {
$('#PageModuleId').on('change', function(){
var formData = $('#PageAddForm').serialize();
// POST to server
$.ajax({
type: 'POST',
url: '<?php echo $this->here; ?>',
dataType: 'text',
data: formData,
success: function(data){
console.log(data[0].ModuleActionModuleController[0].ModuleAction.name);
}
});
});
});
How can I reach for example the 'name' of the first ModuleAction
object in the following JSON?
It appears to me that you are just missing the next child element: ModuleActionModuleController.ModuleAction.name
$(document).ready(function() {
var obj = jQuery.parseJSON( '{"ModuleController":{"id":"3"},"ModuleActionModuleController":[{"id":"4","module_action_id":"1","module_controller_id":"3","ModuleAction":{"id":"1","name":"Overzicht","action":"index"}},{"id":"5","module_action_id":"2","module_controller_id":"3","ModuleAction":{"id":"2","name":"Detail","action":"view"}}]}' );
//alert( obj.ModuleActionModuleController[0].ModuleAction.name );
document.body.innerHTML = obj.ModuleActionModuleController[0].ModuleAction.name;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
This works for me:
var JSON = {
"data": [
{
"ModuleController":{
"id":"3"
},
"ModuleActionModuleController":[
{
"id":"4",
"module_action_id":"1",
"module_controller_id":"3",
"ModuleAction":{
"id":"1",
"name":"Overzicht",
"action":"index"
}
},
{
"id":"5",
"module_action_id":"2",
"module_controller_id":"3",
"ModuleAction":{
"id":"2",
"name":"Detail",
"action":"view"
}
}
]
}
]
};
alert(JSON.data[0].ModuleActionModuleController[0].ModuleAction.id);
I have a json objectlike this
{"test": [{"href": "http://sdfsd.fd"}], "test2": [{"href": "http://sdfsd.fd"}]}
What I want to do is interate over all the links in the json, every likn point to another json object. then i want to get the json from the links, and replace the links with that json, so it comes like something like this:
{"test": {somejson}, "test2": {somejson}}
can this be done? right now I tried with a nested for loop, but the loop doesnøt care that the hhtp request hasn't got a response, before continuing in the loop, resulting in nothing is gonna be edited.
EDIT:
my code so far looks like this:
self.buildJSON = function(json) {
var links = [];
for(var post in json){
// console.log(json[post]['_links']);
for(var link in json[post]['_links']){
links.push(json[post]['_links'][link][0]['href']);
}
}
// var regex = /(http[s]?:\/\/)?([^\/\s]+)(.*)/
// for(link in links){
// var match = regex.exec(links[link]);
// var host = match[1]+match[2];
// var path = match[3];
// links[link] = {"host": host, "path": path};
// }
for(link in links){
request(links[link], function(error, response, body){
if (!error && response.statusCode == 200) {
links[link] = body;
}
})
}
console.log(links);
fs.writeFile(self.jsonfile, JSON.stringify(json));
the Json something like this ('_links' is part of a bigger json):
_links: {
self: [
{
href: "http://wordpress.sutdigselv.dk/wp-json/wp/v2/posts/19"
}
],
collection: [
{
href: "http://wordpress.sutdigselv.dk/wp-json/wp/v2/posts"
}
],
about: [
{
href: "http://wordpress.sutdigselv.dk/wp-json/wp/v2/types/post"
}
],
author: [
{
embeddable: true,
href: "http://wordpress.sutdigselv.dk/wp-json/wp/v2/users/1"
}
],
replies: [
{
embeddable: true,
href: "http://wordpress.sutdigselv.dk/wp-json/wp/v2/comments?post=19"
}
],
version-history: [
{
href: "http://wordpress.sutdigselv.dk/wp-json/wp/v2/posts/19/revisions"
}
],
wp:featuredmedia: [
{
embeddable: true,
href: "http://wordpress.sutdigselv.dk/wp-json/wp/v2/media/130"
}
],
wp:attachment: [
{
href: "http://wordpress.sutdigselv.dk/wp-json/wp/v2/media?parent=19"
}
],
wp:term: [
{
taxonomy: "category",
embeddable: true,
href: "http://wordpress.sutdigselv.dk/wp-json/wp/v2/categories?post=19"
},
{
taxonomy: "post_tag",
embeddable: true,
href: "http://wordpress.sutdigselv.dk/wp-json/wp/v2/tags?post=19"
}
],
curies: [
{
name: "wp",
href: "https://api.w.org/{rel}",
templated: true
}
]
}
You need to parse your JSON first to get the links (maybe put them in an array). (hint: use JSON.stringify() and it becomes a string that you can parse)
Then iterate over each array element and send XHR requests (hint: XMLHttpRequest object). If you want to 'care' for each response, then use xhttp.open(method,url,false) and xhttp.send(). The 'false' will tell that Asynchronous mode is off and so it becomes synchronous. Beware of performance issues now since its synchronous. Read more here
Now create your own JSON object by storing the links in a string and using json.parse(string) to convert it to json