Javascript Multidimensional Array Key-Value - javascript

I am doing an AJAX request to a JSON and getting following code as response:
{
total: "1",
items: [
{
id: 43,
title: "ThisIsTheTitle",
promoted: false,
sticky: false,
weight: 10,
created: {
timestamp: 1482054,
formatted: "17/01/2017"
},
url: "http://...",
airdate: {
timestamp: 1484980,
formatted: "17/01/2017"
},
video: {
id: 43,
number_of_views: 1,
duration: {
seconds: 50,
formatted: "00:00"
},
required_login: false
},
program: {
id: 25,
url: "http://...",
title: "ProgrammaTitel"
},
image: {
uri: "public://...",
full: "http://..."
},
tags: [
{
id: "4",
name: "Map"
},
{
id: "7",
name: "Aflevering2"
}
]
}
]
}
Now I push this data into my own JSArray. Note there is now only 1 response-item but more will be added.
I want to retrieve specific object-data based on the name of a tag of the object (item > tags > name = 'Aflevering2')
So I would like the data from the object where the tag name is 'Aflevering2'.
Any advice? Thanks!

You can find the items with a combination of filter() and some():
obj.items.filter(v => v.tags.some(k => k.name === 'Aflevering2'));
let obj = {
total: "1",
items: [
{
id: 43,
title: "ThisIsTheTitle",
promoted: false,
sticky: false,
weight: 10,
created: {
timestamp: 1482054,
formatted: "17/01/2017"
},
url: "http://...",
airdate: {
timestamp: 1484980,
formatted: "17/01/2017"
},
video: {
id: 43,
number_of_views: 1,
duration: {
seconds: 50,
formatted: "00:00"
},
required_login: false
},
program: {
id: 25,
url: "http://...",
title: "ProgrammaTitel"
},
image: {
uri: "public://...",
full: "http://..."
},
tags: [
{
id: "4",
name: "Map"
},
{
id: "7",
name: "Aflevering2"
}
]
}
]
}
let items = obj.items.filter(v => v.tags.some(k => k.name === 'Aflevering2'));
console.log(items);

Related

How to collect all the objects in the object into a single array

When I click the button, I want to include all the objects in the itemSold and itemGet objects of the customers into the products array. how can I do that?
let customers = [{
active: true,
id: 1,
product: {
itemSold: [{id:1,name : 'car'}, {id:2,name : 'home'}],
itemGet: [{id:3,name : 'phone'}, {id:4,name : 'fly'}],
},
},
{
active: true,
id: 2,
product: {
itemSold: [{id:5,name : 'lamb'}, {id:6,name : 'mouse'}],
itemGet: [{id:7,name : 'mouse pad'}, {id:8,name : 'tv'}],
},
},
];
let clickButton = document.querySelector("#clickButton");
let products = [];
clickButton.addEventListener("click", getProcuts()});
function getProducts(){}
<button id="clickButton" >Click
</button>
let customers = [{
active: true,
id: 1,
product: {
itemSold: [{ id: 1, name: 'car' }, { id: 2, name: 'home' }],
itemGet: [{ id: 3, name: 'phone' }, { id: 4, name: 'fly' }],
},
},
{
active: true,
id: 2,
product: {
itemSold: [{ id: 5, name: 'lamb' }, { id: 6, name: 'mouse' }],
itemGet: [{ id: 7, name: 'mouse pad' }, { id: 8, name: 'tv' }],
},
},
];
let clickButton = document.querySelector("#clickButton");
let products = [];
clickButton.addEventListener("click", getProducts);
function getProducts() {
for (let i = 0; i < customers.length; i++) {
products.push(...customers[i].product.itemGet, ...customers[i].product.itemSold);
}
console.log(products);
}
<button id="clickButton">Click</button>
We loop our customers array and then select product property there we push both itemSold and itemGet arrays into products.
You can map over the customers and concatenate the arrays.
const customers = [
{
active: true,
id: 1,
product: {
itemSold: [
{ id: 1, name: "car" },
{ id: 2, name: "home" },
],
itemGet: [
{ id: 3, name: "phone" },
{ id: 4, name: "fly" },
],
},
},
{
active: true,
id: 2,
product: {
itemSold: [
{ id: 5, name: "lamb" },
{ id: 6, name: "mouse" },
],
itemGet: [
{ id: 7, name: "mouse pad" },
{ id: 8, name: "tv" },
],
},
},
];
const products = customers.map((customer) => {
return customer.product.itemSold.concat(customer.product.itemGet);
});
console.log(products);
const customers = [
{
active: true,
id: 1,
product: {
itemSold: [
{ id: 1, name: "car" },
{ id: 2, name: "home" },
],
itemGet: [
{ id: 3, name: "phone" },
{ id: 4, name: "fly" },
],
},
},
{
active: true,
id: 2,
product: {
itemSold: [
{ id: 5, name: "lamb" },
{ id: 6, name: "mouse" },
],
itemGet: [
{ id: 7, name: "mouse pad" },
{ id: 8, name: "tv" },
],
},
},
];
const products = customers.map((customer) => {
return customer.product.itemSold.concat(customer.product.itemGet).flat();
});
console.log(products.flat());

How to insert entries from into a nested JavaScript Object

I'm facing trouble in making a nested insertion of a particular entry into my data structure. The 'positionValue' in the 'data' object below has to be inserted into 'mystructure' based on whether it is Team1 or Team2, and based on the category 'Lombard Loans/Time Deposits/Demand Deposits' and then further based on 'name' of the product (the last nested structure).
The original object:
data: [
{
balanceSheetPositionResults: [
{
positionValue: 12,
balanceSheetPosition: {
name: "asset_bc_lombard_a_onsight",
category: "LOMBARD_LOANS",
type: "ASSET"
},
},
{
positionValue: 58,
balanceSheetPosition: {
name: "liability_bc_timedeposits",
category: "TIME_DEPOSITS",
type: "ASSET"
},
},
{
positionValue: 58,
balanceSheetPosition: {
name: "liability_bc_demanddeposits",
category: "DEMAND_DEPOSITS",
type: "ASSET"
},
},
{
positionValue: 10,
balanceSheetPosition: {
name: "asset_bc_lombard_a_lt1m",
category: "LOMBARD_LOANS",
type: "ASSET"
},
}
],
bank: {
name: "Team1"
},
game: {
name: "TestGame"
},
bsSum: 2,
period: {
index: 1
},
},
{
balanceSheetPositionResults: [
{
positionValue: 12,
balanceSheetPosition: {
name: "asset_bc_lombard_a_onsight",
category: "LOMBARD_LOANS",
type: "ASSET"
},
},
{
positionValue: 58,
balanceSheetPosition: {
name: "liability_bc_timedeposits",
category: "TIME_DEPOSITS",
type: "ASSET"
},
},
{
positionValue: 58,
balanceSheetPosition: {
name: "liability_bc_demanddeposits",
category: "DEMAND_DEPOSITS",
type: "ASSET"
},
},
{
positionValue: 10,
balanceSheetPosition: {
name: "asset_bc_lombard_a_lt1m",
category: "LOMBARD_LOANS",
type: "ASSET"
},
}
],
bank: {
name: "Team2"
},
game: {
name: "TestGame"
},
bsSum: 2,
period: {
index: 1
}
}
]
The structure that I made after some transformation (this is just a snippet):
{ mystructure:
[
{ name: 'Team2',
LOMBARD_LOANS:
[ { name: 'asset_bc_lombard_a_onsight'
},
{ name: 'asset_bc_lombard_a_lt1m'
}
],
DEMAND_DEPOSITS:
[ { name: 'liability_bc_demanddeposits'
}
],
TIME_DEPOSITS:
[ { name: 'liability_bc_timedeposits'
}
]
},
{ name: 'Team1',
LOMBARD_LOANS:
[ { name: 'asset_bc_lombard_a_onsight'
},
{ name: 'asset_bc_lombard_a_lt1m'
}
],
DEMAND_DEPOSITS:
[ { name: 'liability_bc_demanddeposits'
}
],
TIME_DEPOSITS:
[ { name: 'liability_bc_timedeposits'
}
]
}
]
}
The result that would look like:
{ mystructure:
[
{ name: 'Team2',
LOMBARD_LOANS:
[ { name: 'asset_bc_lombard_a_onsight',
positionValue: 12
},
{ name: 'asset_bc_lombard_a_lt1m',
positionValue: 58
}
],
DEMAND_DEPOSITS:
[ { name: 'liability_bc_demanddeposits',
positionValue: 58
}
],
TIME_DEPOSITS:
[ { name: 'liability_bc_timedeposits',
positionValue: 10
}
]
},
{ name: 'Team1',
LOMBARD_LOANS:
[ { name: 'asset_bc_lombard_a_onsight',
positionValue: 12
},
{ name: 'asset_bc_lombard_a_lt1m',
positionValue: 58
}
],
DEMAND_DEPOSITS:
[ { name: 'liability_bc_demanddeposits',
positionValue: 58
}
],
TIME_DEPOSITS:
[ { name: 'liability_bc_timedeposits',
positionValue: 10
}
]
}
]
}
Assuming each bank name comes only once, pass your original array to this transformer :
function transformData(data) {
return data.map(entry => {
const loanType = {};
entry.balanceSheetPositionResults.forEach(balanceEntry => {
const { name, category, type } = balanceEntry.balanceSheetPosition;
if (!(category in loanType)) {
loanType[category] = [];
}
loanType[category].push({
name,
positionValue: balanceEntry.positionValue
});
});
return {
name: entry.bank.name,
...loanType
};
});
}

how to combine duplicated object in array

I got an array like this
let p = [
{
sku: 12,
data: { name: 'pro', price: 100 },
},
{
sku: 33,
data: { name: 'pro', price: 100 },
},
{
sku: 55,
data: { name: 'pro', price: 100 },
},
{
sku: 12,
data: { name: 'pro', price: 100 },
},
]
I want to combine the duplicated item, and add extra quantity key in each object
So I will have array like this
p = [
{
sku: 12,
data: { name: 'pro', price: 100 },
quantity:2
},
{
sku: 33,
data: { name: 'so', price: 98 },
quantity:1
},
{
sku: 55,
data: { name: 'do', price: 77 },
quantity:1
},
]
How to do this?
You can use Arary.reduce() to iterate over array and create a new one based on calculations like following:
let p = [
{
sku: 12,
data: { name: 'pro', price: 100 },
},
{
sku: 33,
data: { name: 'pro', price: 100 },
},
{
sku: 55,
data: { name: 'pro', price: 100 },
},
{
sku: 12,
data: { name: 'pro', price: 100 },
},
];
var reducedArray = p.reduce((acc,item) => {
var previousItem = acc.find(findItem => findItem.sku === item.sku);
if(!previousItem){
acc.push({...item, quantity: 1})
}else{
previousItem.quantity++
}
return acc;
},[]);
console.log(reducedArray);
Hope this helps.
You can use JavaScript's reduce() method to do that.
let p = [
{
sku: 12,
data: { name: 'pro', price: 100 },
},
{
sku: 33,
data: { name: 'pro', price: 100 },
},
{
sku: 55,
data: { name: 'pro', price: 100 },
},
{
sku: 12,
data: { name: 'pro', price: 100 },
},
];
let result = p.reduce((arr, currentValue) => {
const index = arr.findIndex(item => item.sku === currentValue.sku);
if (index === -1) {
currentValue.quantity = 1;
arr.push(currentValue);
} else {
arr[index].quantity++;
}
return arr;
}, []);
console.log(result);

how to filter nested array like this?

I am having response like below
let m = [
{
name: 'Summary',
subListExpanded: false,
subList: [
]
},
{
name: 'Upload',
subListExpanded: false,
subList: [
]
},
{
name: 'Tasks',
subListExpanded: false,
subList: [
]
},
{
name: 'Dashboard',
subListExpanded: false,
subList: [
]
},
{
name: 'Master',
subListExpanded: false,
subList: [
{
id: 'user-master',
name: 'User-Master'
},
{
id: 'menu-master',
name: 'Menu-Master'
},
{
id: 'entity-master',
name: 'Entity-Master'
},
{
id: 'vendor-master',
name: 'Vendor-Master'
},
{
id: 'xxx-master',
name: 'xxx-Master'
}
]
}
];
If i search m the filter should be like this
[
{
name: 'Summary',
subListExpanded: false,
subList: [
]
},
{
name: 'Master',
subListExpanded: false,
subList: [
{
id: 'user-master',
name: 'User-Master'
},
{
id: 'menu-master',
name: 'Menu-Master'
},
{
id: 'entity-master',
name: 'Entity-Master'
},
{
id: 'vendor-master',
name: 'Vendor-Master'
},
{
id: 'xxx-master',
name: 'xxx-Master'
}
]
}
];
if i search master the filter response should like this?
[
{
name: 'Master',
subListExpanded: false,
subList: [
{
id: 'user-master',
name: 'User-Master'
},
{
id: 'menu-master',
name: 'Menu-Master'
},
{
id: 'entity-master',
name: 'Entity-Master'
},
{
id: 'vendor-master',
name: 'Vendor-Master'
},
{
id: 'xxx-master',
name: 'xxx-Master'
}
]
}
];
if i search xxx-master the filter response should be
[
{
name: 'Master',
subListExpanded: false,
subList: [
{
id: 'xxx-master',
name: 'xxx-Master'
}
]
}
];
if i search slkvcsmcskc filter response like
[]
my typescript code is not working properly .please help me to fix this>
m.filter(x=> x.name.toLowerCase() === search.toLowerCase() || x.subList.some(x1=> x1.name.toLowerCase()===search.toLowerCase()))
The following code gives the desired output. Note that I added some complexity which may not be needed for your use case. However, the example should work for lists with arbitrary deep nesting (see 'bar' example).
let m = [
{
name: 'Summary',
subListExpanded: false,
subList: [
]
},
{
name: 'Upload',
subListExpanded: false,
subList: [
{
name: 'foo',
subList: [
{
name: 'bar',
}
],
}
]
},
{
name: 'Tasks',
subListExpanded: false,
subList: [
]
},
{
name: 'Dashboard',
subListExpanded: false,
subList: [
]
},
{
name: 'Master',
subListExpanded: false,
subList: [
{
id: 'user-master',
name: 'User-Master'
},
{
id: 'menu-master',
name: 'Menu-Master'
},
{
id: 'entity-master',
name: 'Entity-Master'
},
{
id: 'vendor-master',
name: 'Vendor-Master'
},
{
id: 'xxx-master',
name: 'xxx-Master'
}
]
}
];
function search (input, query) {
const queryReg = new RegExp(query, 'i');
function searchInternal (data) {
let result = [];
data.forEach(item => {
const parentMatch = queryReg.test(item.name);
let subMatch = false;
if (item.subList) {
let subResult = searchInternal(item.subList);
subMatch = subResult.length > 0;
item.subList = subMatch ? subResult : [];
}
// push parent if it matches for itself or a child (list) matches
if (parentMatch || subMatch) result.push(item);
});
return result;
}
return searchInternal(JSON.parse(JSON.stringify(input)) /* create a working copy with JSON.parse(...) */);
}
console.log('master', search(m, 'master'));
console.log('xxx-master', search(m, 'xxx-master'));
console.log('m', search(m, 'm'));
console.log('bar', search(m, 'bar'));
console.log('slkvcsmcskc', search(m, 'slkvcsmcskc'));
Actually it should go like this:
obj = {
_id: "sjkd9skj",
data: {
dektop: [
{
x: 2,
y: 3,
t: { key: 'aabbcc'}
},
...
],
mobile: [
{
x: 4,
y: 3,
t: { key: 'ffff'}
},
...
],
print: [
{
x: 7,
y: 5,
t: { key: 'ppp'}
},
...
]
}
}

Filtering Nested Array with Lodash/Javascript

I have the following object array:
var sizeList = [
{ id: 1, title:"Test1",
type:[{name:"Big", present:false}, {name:"Small", present:true}, {name:"Medium", present:false}]
},
{ id: 2,title:"Test2",
type:[{name:"Big", present:false}, {name:"Small", present:true}, {name:"Medium", present:false}]
},
{ id: 3,title:"Test3",
type:[{name:"Big", present:false}, {name:"Small", present:true}, {name:"Medium", present:true}]
}
]
I want to filter this list where Medium is True. I currently have this set up.
var specificSizes = _.filter(sizeList.type, { 'name': 'Medium', 'present': true })
This keeps returning an empty array. I also tried this:
specificSizes = _.filter(sizeList.type, function (type) {
return _.some(type, {'name': 'Medium', 'present':true})
});
With lodash, you could wrap the condition in the same structure for the test, as the original object.
_.filter(sizeList, { type: [{ name: 'Medium', present: true }] })
var sizeList = [{ id: 1, title: "Test1", type: [{ name: "Big", present: false }, { name: "Small", present: true }, { name: "Medium", present: false }] }, { id: 2, title: "Test2", type: [{ name: "Big", present: false }, { name: "Small", present: true }, { name: "Medium", present: false }] }, { id: 3, title: "Test3", type: [{ name: "Big", present: false }, { name: "Small", present: true }, { name: "Medium", present: true }] }],
result = _.filter(sizeList, { type: [{ name: 'Medium', present: true }] });
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>
In plain Javascript, you could use Array#filter for the outer array and check with Array#some if one condition met.
var sizeList = [{ id: 1, title: "Test1", type: [{ name: "Big", present: false }, { name: "Small", present: true }, { name: "Medium", present: false }] }, { id: 2, title: "Test2", type: [{ name: "Big", present: false }, { name: "Small", present: true }, { name: "Medium", present: false }] }, { id: 3, title: "Test3", type: [{ name: "Big", present: false }, { name: "Small", present: true }, { name: "Medium", present: true }] }],
result = sizeList.filter(function (a) {
return a.type.some(function (b) {
return b.name === 'Medium' && b.present;
});
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Categories