Need to get each "link" entry from nested json using js - javascript

There is a json code. Consisting by type:
{"123":{...},"321":{...}}
In it, you need to get "links" from each entry. I couldn't understand this note, please help me.
{
"3782474584475521065": {
"listingid": "3782474584475521065",
"price": 16,
"asset": {
"currency": 0,
"appid": 730,
"contextid": "2",
"id": "25996697315",
"amount": "1",
"market_actions": [
{
"link": "steam://rungame/730/76561202255233023/+csgo_econ_action_preview%20M%listingid%A%assetid%D2354938592644984102",
"name": "Осмотреть в игре…"
}
]
}
},
"3782474584475520325": {
"listingid": "3782474584475520325",
"price": 16,
"asset": {
"currency": 0,
"appid": 730,
"contextid": "2",
"id": "25996698023",
"amount": "1",
"market_actions": [
{
"link": "steam://rungame/730/76561202255233023/+csgo_econ_action_preview%20M%listingid%A%assetid%D9866835690490179400",
"name": "Осмотреть в игре…"
}
]
}
}
}

Return an array of objects {id:link}
const data = {
"3782474584475521065": {
"listingid": "3782474584475521065",
"price": 16,
"asset": {
"currency": 0,
"appid": 730,
"contextid": "2",
"id": "25996697315",
"amount": "1",
"market_actions": [
{
"link": "steam://rungame/730/76561202255233023/+csgo_econ_action_preview%20M%listingid%A%assetid%D2354938592644984102",
"name": "Осмотреть в игре…"
}
]
}
},
"3782474584475520325": {
"listingid": "3782474584475520325",
"price": 16,
"asset": {
"currency": 0,
"appid": 730,
"contextid": "2",
"id": "25996698023",
"amount": "1",
"market_actions": [
{
"link": "steam://rungame/730/76561202255233023/+csgo_econ_action_preview%20M%listingid%A%assetid%D9866835690490179400",
"name": "Осмотреть в игре…"
}
]
}
}
}
const result = Object.entries(data).map(([key, {asset, ...rest}]) => ({[key]: asset.market_actions[0].link}))
console.log(result)

If I understood your question correctly, you need to extract the links from the json text. This is a solution:
const a = {
"3782474584475521065": {
listingid: "3782474584475521065",
price: 16,
asset: {
currency: 0,
appid: 730,
contextid: "2",
id: "25996697315",
amount: "1",
market_actions: [
{
link: "steam://rungame/730/76561202255233023/+csgo_econ_action_preview%20M%listingid%A%assetid%D2354938592644984102",
name: "Осмотреть в игре…",
},
],
},
},
"3782474584475520325": {
listingid: "3782474584475520325",
price: 16,
asset: {
currency: 0,
appid: 730,
contextid: "2",
id: "25996698023",
amount: "1",
market_actions: [
{
link: "steam://rungame/730/76561202255233023/+csgo_econ_action_preview%20M%listingid%A%assetid%D9866835690490179400",
name: "Осмотреть в игре…",
},
],
},
},
};
// get links from a
const links = Object.values(a).map(({ asset }) => {
const { market_actions } = asset;
const { link } = market_actions[0];
return link;
});
console.log(links);
This simply iterates through the object's values and accesses the link values through object extraction.

Related

Show JSON in VUE.js

I made an API on Node.js, If I send some params I get the response, it's the same person but different language info, I would like to present it like in the second example I haven't been able to figure it out.
How I'm getting the data
[
{
"Id": 1,
"ced": "123",
"Name": "Andres",
"NativeLanguage": 1,
"Level": 100,
"NameLang": "spanish",
},
{
"Id": 1,
"ced": "123",
"Name": "Andres",
"NativeLanguage": 1,
"Level": 100,
"NameLang": "english",
}
]
how I want to see it
[
{
"Id": 1,
"ced": "123",
"Name": "Andres",
}
"Idiomas":
[
{
"NativeLanguage": 1,
"Level": 100,
"NameLang": "spanish",
},
{
"NativeLanguage": 1,
"Level": 100,
"NameLang": "spanish",
}
]
]
export default {
el: "myFormPerson",
data() {
return {
results:[],
ced:'',
}
},
methods: {
submitForm() {
axios.get('http://localhost:8080/person/' + this.ced)
.then((response) => {
this.results = response.data;
//console.log(this.results);
})
.catch(function (error) {
console.log(error);
})
.finally(function () {
});
//console.log(this.ced);
},
}
}
How I see it right now [1]: https://i.stack.imgur.com/ezHgH.png
Rather than pointlessly trying to get the format you want in the MySQL result (not possible) - work with the JSON to convert it to what you want
this.results=Object.values(response.data.reduce((acc,{Id,ced,Name,...rest})=>(acc[Id]||={Id,ced,Name,Idiomas:[]},acc[Id].Idiomas.push({...rest}),acc),{}));
working example
const have = [{
"Id": 1,
"ced": "123",
"Name": "Andres",
"NativeLanguage": 1,
"Level": 100,
"NameLang": "spanish",
},
{
"Id": 1,
"ced": "123",
"Name": "Andres",
"NativeLanguage": 1,
"Level": 100,
"NameLang": "english",
}
];
const want = Object.values(have.reduce((acc,{Id,ced,Name,...rest}) => (acc[Id]||={Id,ced,Name,Idiomas:[]},acc[Id].Idiomas.push({...rest}),acc),{}));
console.log(want);

How to change object values with another object key path?

How to change the destination values with source object key path?
The source object is like below
{
"total-info": [{
"emp-sal-info": {
"id": "emp01",
"currency": "dollar",
"details": {
"sal-details": [{
"name": "peter",
"income": "$400"
},
{
"name": "peter wife",
"income": "$500"
}
]
}
}
}, {
"emp-sal-info": {
"id": "emp01",
"currency": "dollar",
"details": {
"sal-details": [{
"name": "John",
"income": "$900"
},
{
"name": "John wife",
"income": "$400"
}
]
}
}
}]
}
The destination is like this:
{
"company": [{
"Peter": {
"id": "emp01",
"sal": "$3000"
}
}, {
"John": {
"id": "emp02",
"sal": "$5000"
}
}]
}
Then how do I change the destination object to the below format?
{
"company": [{
"Peter": {
"id": "emp01",
"sal": "['total-info']['0']['emp-sal-info']['details']['sal-details']['0']['salary']+['total-info']['0']['emp-sal-info']['details']['sal-details']['0']['salary']"
}
}, {
"John": {
"id": "emp02",
"sal": "['total-info']['1']['emp-sal-info']['details']['sal-details']['0']['salary']+['total-info']['1']['emp-sal-info']['details']['sal-details']['0']['salary']"
}
}]
}
Can you please tell me how transform to arrays like above. Thanks you

How can i make json file like this when i input

How can i make the cart_items like my expetation.. just it no more.. my problem just it :D
i just wanna make my cart_items like this.. hope you are can help me thanks. did I make the wrong method? and one more thing, i wanna make the qty inside the cart_items
this is my expectation
"cart": [
{
"id": 1,
"date": "12/10/2020",
"store": {
"id": 1,
"name": "Dirumah Aja",
"promo": 1
},
"cart_items": [
{
"id": 1,
"product": {
"id": 1,
"name": "Bakso Urat",
"price": 10000,
"promo": {
"nama": "promo"
}
},
"qty": 5
}
]
}
]
and this is what I got
"cart": [
{
"cart_items": {
"name": "Steak Sapi Impor",
"price": "38000",
"stock": "4",
"image": "https://firebasestorage.googleapis.com/v0/b/francise-fb70a.appspot.com/o/steak.jpg?alt=media&token=46e0d769-96d3-440f-8edb-5fce2481ace0",
"promo": 3,
"id": 8,
"qty": 1
},
"store": {
"name": "Amanda Foods Store",
"email": "amanda#food.com",
"store_image": "https://firebasestorage.googleapis.com/v0/b/francise-fb70a.appspot.com/o/full_hd_retina.jpeg?alt=media&token=3e602e86-661b-48ee-9e9c-af9f94a170d1",
"product": [
5,
7,
8,
2
],
"store_promo": 1,
"location": {
"street_name": "Jl. Kebon Gedang II B",
"province": "Jawa Barat",
"city": "Bandung",
"post_code": "40285"
},
"id": 1
},
"date_order": "Nov 03 2020 08:48:03",
"id": 2
}
]
This is my data
data() {
return {
promo_id: [],
promo_partner: [],
products: {},
qty: 1,
cart_items: [
{}
]
};
and this is my method
addToCart() {
const date = (new Date()).toString().split(' ').splice(1,4).join(' ')
this.products.cart_items = this.product;
this.products.cart_items.qty = this.qty;
this.products.store = this.partner;
this.products.date_order = date;
console.log(this.cart_items)
axios
.post("http://localhost:3000/cart/", this.products)
.then(() => {
swal("Belanja Berhasil!", {
icon: "success",
});
})
.catch((error) => console.log(error));
}
}
You need to use .push() to add items to an array. You're replacing the array with this.product.
if (!this.products.cart_items) { // initialize cart_items if necessary
this.products.cart_items = [];
}
this.products.cart_items.push({id: this.product.id, product: this.product, qty: this.qty});

Return formatted object with only positive values

I've an object of objects. Each of my nested object has a price as a nested array which may contain negative values.
I need to format the object and return a new one with the child objects containing only positive values.
For e.g.,
In the code below, ideally it should only return object with 'TypeB' object as only that has the price with non-negative values.
I tried this, but I guess am missing something.
Also, can I optimize this using 'reduce' method instead?
Input Object:
{
"TypeA": [
{
"price": [
[
{
"amount": -45,
"currency": "USD"
}
]
],
"name": "ABC",
"priceDetails": [
{
"name": "BASE",
"price": [
[
{
"amount": -40.00,
"currency": "USD"
}
]
]
},
{
"name": "TAX",
"price": [
[
{
"amount": -5.00,
"currency": "USD"
}
]
]
}
]
}
],
"TypeB": [
{
"price": [
[
{
"amount": 0,
"currency": "USD"
}
]
],
"name": "ABC",
"priceDetails": [
{
"name": "BASE",
"price": [
[
{
"amount": 0,
"currency": "USD"
}
]
]
}
]
}
]
}
Expected Output:
{
"TypeB": [
{
"price": [
[
{
"amount": 0,
"currency": "USD"
}
]
],
"name": "ABC",
"priceDetails": [
{
"name": "BASE",
"price": [
[
{
"amount": 0,
"currency": "USD"
}
]
]
}
]
}
]
}
Code:
const data = {
"TypeA": [{
"price": [
[{
"amount": -45,
"currency": "USD"
}]
],
"name": "ABC",
"priceDetails": [{
"name": "BASE",
"price": [
[{
"amount": -40.00,
"currency": "USD"
}]
]
},
{
"name": "TAX",
"price": [
[{
"amount": -5.00,
"currency": "USD"
}]
]
}
]
}],
"TypeB": [{
"price": [
[{
"amount": 0,
"currency": "USD"
}]
],
"name": "ABC",
"priceDetails": [{
"name": "BASE",
"price": [
[{
"amount": 0,
"currency": "USD"
}]
]
}]
}]
};
const formattedData = Object.values(data).filter(item => {
return item.map(elem => {
const itemPrice = elem.price;
const isPositive = itemPrice[0][0].amount >= 0;
return isPositive ? elem : false;
});
});
console.log(formattedData);
You could filter the data by using various checks and build a new object if a wanted leaf object is found.
function filter(object) {
if (!object || typeof object !== 'object') return;
if ('amount' in object) return object.amount >= 0 ? object : undefined;
if (Array.isArray(object)) {
var items = object.reduce((r, v) => {
var temp = filter(v);
if (temp) r.push(temp);
return r;
}, []);
return items.length ? items : undefined;
} else {
var entries = Object.entries(object).reduce((r, [k, v]) => {
var temp = filter(v);
if (temp) r.push([k, temp]);
return r;
}, []);
return entries.length ? Object.fromEntries(entries) : undefined;
}
}
var data = { TypeA: [{ price: [[{ amount: -45, currency: "USD" }]], name: "ABC", priceDetails: [{ name: "BASE", price: [[{ amount: -40, currency: "USD" }]] }, { name: "TAX", price: [[{ amount: -5, currency: "USD" }]] }] }], TypeB: [{ price: [[{ amount: 0, currency: "USD" }]], name: "ABC", priceDetails: [{ name: "BASE", price: [[{ amount: 0, currency: "USD" }]] }] }] },
result = filter(data);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
cc = {
"TypeA": [
{
"price": [
[
{
"amount": -45,
"currency": "USD"
}
]
],
"name": "ABC",
"priceDetails": [
{
"name": "BASE",
"price": [
[
{
"amount": -40.00,
"currency": "USD"
}
]
]
},
{
"name": "TAX",
"price": [
[
{
"amount": -5.00,
"currency": "USD"
}
]
]
}
]
}
],
"TypeB": [
{
"price": [
[
{
"amount": 0,
"currency": "USD"
}
]
],
"name": "ABC",
"priceDetails": [
{
"name": "BASE",
"price": [
[
{
"amount": 0,
"currency": "USD"
}
]
]
}
]
}
]
}
const dd = Object.keys(cc).reduce((acc, item) => {
if (cc[item][0].price[0][0].amount >= 0) {
acc[item] = cc[item];
}
return acc;
}, {});
console.log(dd)
Try this
const result = Object.keys(data).filter(i => data[i][0].price[0][0].amount >= 0).map(y => data[y])
console.log(result) // positive amount array
Edits : With reducer
const dd = Object.keys(data).reduce((acc, item) => {
if (data[item][0].price[0][0].amount >= 0) {
acc[item] = data[item];
}
return acc;
}, {});
It is possible to use Object.entries to make your object as array and then just filter by checking that every amount is greater than 0:
const filtered = Object.entries(data).filter(([k, v]) =>
v.every(s=> s.price.every(s1 => s1.every(s2 => s2.amount >= 0 )))
&& v.every(pd => pd.priceDetails.every(pdp =>
pdp.price.every(pr => pr.every(prr => prr.amount >= 0))))
);
An example:
const data = {
"TypeA": [{
"price": [ [{ "amount": -45, "currency": "USD" }]
],
"name": "ABC",
"priceDetails": [{
"name": "BASE",
"price": [[{ "amount": -40.00, "currency": "USD" }]]
},
{
"name": "TAX",
"price": [ [{ "amount": -5.00, "currency": "USD" }]]
}
]
}],
"TypeB": [{
"price": [ [{"amount": 0, "currency": "USD" }]],
"name": "ABC",
"priceDetails": [{
"name": "BASE",
"price": [[{"amount": 0, "currency": "USD"}]]
}]
}]
};
const filtered = Object.entries(data).filter(([k, v]) =>
v.every(s=> s.price.every(s1 => s1.every(s2 => s2.amount >= 0 )))
&& v.every(pd => pd.priceDetails.every(pdp => pdp.price.every(pr => pr.every(prr => prr.amount >= 0))))
);
const result = Object.fromEntries(filtered);
console.log(result);

Fuzzy search deep array only on certain properties

I have a JSON dataset which could be very large when it returns, with the following structure for each object:
{
"ctr": 57,
"averageECPC": 23,
"cost": 2732.54,
"margin": 66,
"profit": 2495.9,
"property": {
"value": "Izzby",
"uri": "/Terrago/2"
},
"status": {
"content": "<p>Some Content</p>",
"stage": 1
},
"alerts": {
"status": 2
},
"revenue": {
"value": 2573.13,
"compare": 0
},
"children": [{
"ctr": 79,
"averageECPC": 54,
"cost": 3554.78,
"margin": 88,
"profit": 3145.81,
"property": {
"value": "Comvex",
"uri": "/Octocore/4"
},
"status": {
"content": "<p>Some Content</p>",
"stage": 1
},
"alerts": {
"status": 2
},
"revenue": {
"value": 1247.92,
"compare": 0
}
}]
}
Now I want to search all objects in the array and return only objects which include a string of some sort, but I only want to search certain properties.
I basically have another array which contains the keys I want to search, e.g.
const iteratees = ['ctr', 'property.value', 'status.stage']
I have lodash available within the project, but I have no idea where to start.
Any ideas?
You could use filter(), some() and reduce() to do this.
const iteratees = ['ctr', 'property.value', 'status.stage'];
var searchFor = 'lo';
var result = arr.filter(function(o) {
return iteratees.some(function(e) {
var res = e.split('.').reduce(function(a, b) {
if(a) return a[b];
}, o);
if(res) {
if((res).toString().indexOf(searchFor) != -1) return true;
}
})
})
var arr = [{
"ctr": 'lorem',
"averageECPC": 23,
"cost": 2732.54,
"margin": 66,
"profit": 2495.9,
"property": {
"value": "Izzby",
"uri": "/Terrago/2"
},
"status": {
"content": "<p>Some Content</p>",
"stage": 1
},
"alerts": {
"status": 2
},
"revenue": {
"value": 2573.13,
"compare": 0
},
"children": [{
"ctr": 79,
"averageECPC": 54,
"cost": 3554.78,
"margin": 88,
"profit": 3145.81,
"property": {
"value": "Comvex",
"uri": "/Octocore/4"
},
"status": {
"content": "<p>Some Content</p>",
"stage": 1
},
"alerts": {
"status": 2
},
"revenue": {
"value": 1247.92,
"compare": 0
}
}]
}, {
name: 'lorem',
ctr: 12,
property: {
value: 1
},
status: {
stage: 1
}
}, {
name: 'ipsum'
}]
const iteratees = ['ctr', 'property.value', 'status.stage'];
var searchFor = 'lo';
var result = arr.filter(function(o) {
return iteratees.some(function(e) {
var res = e.split('.').reduce(function(a, b) {
if (a) return a[b];
}, o);
if (res) {
if ((res).toString().indexOf(searchFor) != -1) return true;
}
})
})
console.log(result)

Categories

Resources