How should I slice the array of objects of objects - javascript

i have a array which looks like this :
[
{
"1": {
"id": 1,
"price": 569.2,
"marketcap": 94943213384.68,
"timestamp": 1637136047,
"datetime": "2021-11-17 08:00:47"
},
"2": {
"id": 2,
"price": 59745.7,
"marketcap": 1127634159487.02,
"timestamp": 1637136064,
"datetime": "2021-11-17 08:01:04"
},
"3": {
"id": 3,
"price": 592.53,
"marketcap": 11199494644.95126,
"timestamp": 1637136053,
"datetime": "2021-11-17 08:00:53"
}
},
{
"1": {
"id": 1,
"last30dcommits": null,
"activity": "No Github Repo Found"
},
"2": {
"id": 2,
"last30dcommits": 109,
"activity": "High Activity"
},
"3": {
"id": 3,
"last30dcommits": 44,
"activity": "Medium Activity"
}
},
{
"1": {
"id": 1,
"change24h": -6.75,
"change7d": -10.18,
"change30d": 17.32,
"timestamp24h": 1637035200,
"timestamp7d": 1636516800,
"timestamp30d": 1634529600
},
"2": {
"id": 2,
"change24h": -3.22,
"change7d": -12.58,
"change30d": -5.17,
"timestamp24h": 1637035200,
"timestamp7d": 1636516800,
"timestamp30d": 1634529600
},
"3": {
"id": 3,
"change24h": -6.37,
"change7d": -17.81,
"change30d": -5.04,
"timestamp24h": 1637035200,
"timestamp7d": 1636516800,
"timestamp30d": 1634529600
}
},
{
"1": {
"tweetsRating": 44.04,
"newsRating": 38.42
},
"2": {
"tweetsRating": 14.76,
"newsRating": -1.27
},
"3": {
"tweetsRating": 0,
"newsRating": 44.35
}
},
]
I am implementing a pagination in the front end in which I am slicing each objects in each object in the array to a given value so that I get a result something like this if I slice (0,2)
[
{
"1": {
"id": 1,
"price": 569.2,
"marketcap": 94943213384.68,
"timestamp": 1637136047,
"datetime": "2021-11-17 08:00:47"
},
"2": {
"id": 2,
"price": 59745.7,
"marketcap": 1127634159487.02,
"timestamp": 1637136064,
"datetime": "2021-11-17 08:01:04"
}
},
{
"1": {
"id": 1,
"last30dcommits": null,
"activity": "No Github Repo Found"
},
"2": {
"id": 2,
"last30dcommits": 109,
"activity": "High Activity"
}
},
{
"1": {
"id": 1,
"change24h": -6.75,
"change7d": -10.18,
"change30d": 17.32,
"timestamp24h": 1637035200,
"timestamp7d": 1636516800,
"timestamp30d": 1634529600
},
"2": {
"id": 2,
"change24h": -3.22,
"change7d": -12.58,
"change30d": -5.17,
"timestamp24h": 1637035200,
"timestamp7d": 1636516800,
"timestamp30d": 1634529600
}
},
{
"1": {
"tweetsRating": 44.04,
"newsRating": 38.42
},
"2": {
"tweetsRating": 14.76,
"newsRating": -1.27
}
},
]
means only 2 objects should be sliced out.
my function is as following but its not working.
const sliceData = (array,start,end)=>{
array.forEach(arr=>{
Object.keys(arr).slice(start - 1, end + 1).reduce((result, key) => {
result[key] = arr[key];
return result;
}
})
}
Here start and end represents the index of starting object in a page and index of last object in the page respectively.
Can anyone help me with the code? I'll be very grateful.

You could slice the entries for new objects.
const
data = [{ "1": { id: 1, price: 569.2, marketcap: 94943213384.68, timestamp: 1637136047, datetime: "2021-11-17 08:00:47" }, "2": { id: 2, price: 59745.7, marketcap: 1127634159487.02, timestamp: 1637136064, datetime: "2021-11-17 08:01:04" }, "3": { id: 3, price: 592.53, marketcap: 11199494644.95126, timestamp: 1637136053, datetime: "2021-11-17 08:00:53" } }, { "1": { id: 1, last30dcommits: null, activity: "No Github Repo Found" }, "2": { id: 2, last30dcommits: 109, activity: "High Activity" }, "3": { id: 3, last30dcommits: 44, activity: "Medium Activity" } }, { "1": { id: 1, change24h: -6.75, change7d: -10.18, change30d: 17.32, timestamp24h: 1637035200, timestamp7d: 1636516800, timestamp30d: 1634529600 }, "2": { id: 2, change24h: -3.22, change7d: -12.58, change30d: -5.17, timestamp24h: 1637035200, timestamp7d: 1636516800, timestamp30d: 1634529600 }, "3": { id: 3, change24h: -6.37, change7d: -17.81, change30d: -5.04, timestamp24h: 1637035200, timestamp7d: 1636516800, timestamp30d: 1634529600 } }, { "1": { tweetsRating: 44.04, newsRating: 38.42 }, "2": { tweetsRating: 14.76, newsRating: -1.27 }, "3": { tweetsRating: 0, newsRating: 44.35 } }],
result = data.map(o => Object.fromEntries(Object.entries(o).slice(0, 2)));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

I really think the data format/structure sent from BackEnd should be changed. Instead of sending Array of objects you should consider sending Array of Array of objects from Backend. This is because essentially the id of the object is key. However, Here is how you can slice the data if you do not have permission to change data sent from Backend.
const sliceData = (array,start,end)=>{
return array.map(el => {
let newObj = Object.values(el).filter(x => x.id>start && x.id<=end).reduce((acc,x) => {
acc[x.id] = x;
return acc;
} ,{})
return newObj;
});
}

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);

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

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.

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});

Group array of nested objects with multiple levels in JavaScript

I'm trying to group a big nested object with multiple properties such as this one :
[
{
"id": 14,
"name": "Name14",
"theme": true,
"sub": {
"id": 70,
"name": "Name70"
}
},
{
"id": 14,
"name": "Name14",
"theme": true,
"sub": {
"id": 61,
"name": "Name61"
}
},
{
"id": 14,
"name": "Name14",
"theme": true,
"sub": {
"id": 4,
"name": "Name4",
"sub": {
"id": 5,
"name": "Name5",
"sub": {
"id": 29,
"name": "Name29"
}
}
}
},
{
"id": 14,
"name": "Name14",
"theme": true,
"sub": {
"id": 4,
"name": "Name4",
"sub": {
"id": 5,
"name": "Name5",
"sub": {
"id": 8,
"name": "Name8",
"sub": {
"id": 163,
"name": "Name163"
}
}
}
}
},
{
"id": 10,
"name": "Name10",
"sub": {
"id": 4,
"name": "Name4"
}
}
]
As you can see, the "sub" are not arrays as of now, but they would be in the expected output even if there's only one object in it.
I'd like to group the array by object's id recursively to get this kind of output :
[
{
"id": 14,
"name": "Name14",
"theme": true,
"sub": [
{
"id": 70,
"name": "Name70"
},
{
"id": 61,
"name": "Name61"
},
{
"id": 4,
"name": "Name4",
"sub": [
{
"id": 5,
"name": "Name5",
"sub": [
{
"id": 29,
"name": "Name29"
},
{
"id": 8,
"name": "Name8",
"sub": [
{
"id": 163,
"name": "Name163"
}
]
}
]
}
]
}
]
},
{
"id": 10,
"name": "Name10",
"sub": [
{
"id": 4,
"name": "Name4"
}
]
}
]
So far, I tried some shenanigans with lodash and d3.nest() but I just can't seem to group it.
Have you guys ever face something similar? And if so, how did you manage to code this?
Thanks a lot
You could take a recursive approach with a function which merges an object into an array by looking for same id.
const
merge = (target, { sub, ...o }) => {
let temp = target.find(({ id }) => id === o.id);
if (sub) sub = merge(temp?.sub || [], sub)
if (!temp) target.push(temp = { ...o, sub });
return target;
};
var data = [{ id: 14, name: "Name14", theme: true, sub: { id: 70, name: "Name70" } }, { id: 14, name: "Name14", theme: true, sub: { id: 61, name: "Name61" } }, { id: 14, name: "Name14", theme: true, sub: { id: 4, name: "Name4", sub: { id: 5, name: "Name5", sub: { id: 29, name: "Name29" } } } }, { id: 14, name: "Name14", theme: true, sub: { id: 4, name: "Name4", sub: { id: 5, name: "Name5", sub: { id: 8, name: "Name8", sub: { id: 163, name: "Name163" } } } } }, { id: 10, name: "Name10", sub: { id: 4, name: "Name4" } }],
result = data.reduce(merge, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You could create a Map for each sub property -- keyed by id -- and merge the objects into those maps. Then finally convert those sub-maps back to sub-arrays:
function mergeArray(arr) {
function mergeObject(a, b) {
while (b = b.sub) {
if (!a.sub) a.sub = new Map;
let child = a.sub.get(b.id);
if (child) a = child;
else a.sub.set(b.id, a = { id: b.id, name: b.name });
}
}
function convertMap(map) {
return Array.from(map.values(), obj => {
if (obj.sub) obj.sub = convertMap(obj.sub);
return obj;
});
}
let map = new Map(arr.map(({id, name}) => [id, {id, name}]));
for (let item of arr) mergeObject(map.get(item.id), item);
return convertMap(map);
}
// Demo with input from question
let input = [{"id": 14,"name": "Name14","theme": true,"sub": {"id": 70,"name": "Name70"}},{"id": 14,"name": "Name14","theme": true,"sub": {"id": 61,"name": "Name61"}},{"id": 14,"name": "Name14","theme": true,"sub": {"id": 4,"name": "Name4","sub": {"id": 5,"name": "Name5","sub": {"id": 29,"name": "Name29"}}}},{"id": 14,"name": "Name14","theme": true,"sub": {"id": 4,"name": "Name4","sub": {"id": 5,"name": "Name5","sub": {"id": 8,"name": "Name8","sub": {"id": 163,"name": "Name163"}}}}},{"id": 10,"name": "Name10","sub": {"id": 4,"name": "Name4"}}];
console.log(mergeArray(input));
I would do it with recursive functions, because I think those are more versatile:
const data = [{
"id": 14,
"name": "Name14",
"theme": true,
"sub": {
"id": 70,
"name": "Name70"
}
},
{
"id": 14,
"name": "Name14",
"theme": true,
"sub": {
"id": 61,
"name": "Name61"
}
},
{
"id": 14,
"name": "Name14",
"theme": true,
"sub": {
"id": 4,
"name": "Name4",
"sub": {
"id": 5,
"name": "Name5",
"sub": {
"id": 29,
"name": "Name29"
}
}
}
},
{
"id": 14,
"name": "Name14",
"theme": true,
"sub": {
"id": 4,
"name": "Name4",
"sub": {
"id": 5,
"name": "Name5",
"sub": {
"id": 8,
"name": "Name8",
"sub": {
"id": 163,
"name": "Name163"
}
}
}
}
},
{
"id": 10,
"name": "Name10",
"sub": {
"id": 4,
"name": "Name4"
}
}
]
// setting up arrays
const recursiveModify = (node) => {
if (typeof node.sub === "undefined") {
return node
} else {
node.sub = [recursiveModify(node.sub)]
return node
}
}
const recursiveReduce = (nodes) => {
return nodes.reduce((a, c) => {
const item = a.find(e => e.id === c.id)
if (!item) {
a.push(c)
} else {
item.sub = recursiveReduce([...item.sub, ...c.sub])
}
return a
}, [])
}
const dataWithArray = data.map(node => {
return recursiveModify(node)
})
const result = recursiveReduce(dataWithArray)
console.log(result)
Unfortunately I could only do it with two passes - one for creating the sub as arrays, then one for actually grouping the data. I'm pretty sure it can be done in one pass - I just have no more time to work it out.

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