vuejs - how to add array to the target data? - javascript

I want to add data like this
category1
company1
company2
company3
category2
company1
company2
company3
my code
getlist() {
var list = this.lists;
var category
// var company
this.$http.get("/getlist")
.then((res) => {
var obj = res.data;
for(var [key] in obj) {
var company =[];
for(var i in obj[key].company) {
company.push( obj[key].company[i].name)
}
console.log(company);
list.push({
"category_name" : obj[key].name,
"companies": [
{name: company}
]
})
list.category_name = '',
list.companies = '',
company= ''
}
})
},
list form is look like this
{
category_name: 'Category1',
companies: [
{name: 'company1'},
]
},
and data is look like this
[
{
"name": "Category2",
"company": [
{
"name": "company1"
}
{
"name": "company2"
}
]
}
{
"name": "Category2",
"company": [
{
"name": "company1"
}
{
"name": "company2"
}
]
}
]
I don't know how to use forloop in this case.
Can it use double for loop in list.push()?
It is very tired for me..

As I understand, you just want to rename the keys of data objects you retrieve from the server.
This should do it:
getlist() {
this.$http.get('/getlist')
.then(res => {
let list = [];
for (let item of res.data) {
let newItem = {
category_name: item.name,
companies: item.company
}
list.push(newItem);
}
this.lists = list;
})
.catch(err => {
console.error('Error retrieving "/getlist":', err)
});
}

Related

moving a key value pair out of an array

I am trying to move everything in the Array Results outside and into the original object
this is the object
{
"Name": "John",
"Results": [
{
"Type": "DB",
"Immediate_Action": "No",
}
]
}
It should look like this
{
"Name": "John",
"Type": "DB",
"Immediate_Action": "No",
}
What I have so far is this
const mapOscarResults = ({ data }) => {
return data.map(entry => {
let mapped = {...entry};
entry.Results.forEach(key => {
let Type = mapped[key.Type]
if (mapped[key]) {
mapped[key].push(entry.Results[key]);
} else {
mapped[key] = [entry.Results[key]];
}
});
return mapped;
});
};
You can simply spread the Results array into an Object.assign() call.
const input = { "Name": "John", "Results": [{ "Type": "DB", "Immediate_Action": "No", }, { "Another": "value" }] };
const { Results, ...refactored } = input;
Object.assign(refactored, ...Results);
console.log(refactored)
This code works for your example:
const { Results: results, ...rest } = {
"Name": "John",
"Results": [
{
"Type": "DB",
"Immediate_Action": "No",
}
]
}
const res = {...rest, ...results.reduce((prev, curr) => ({
...prev,
...curr
}), {})}
console.log(res)
But I don't know what you expect when the Results array has more than one element.
In that condition, if this code does not fill your needs, ask me to change it.
however, it will join first Result with index 0, you can expand it
const data = {
"Name": "John",
"Results": [
{
"Type": "DB",
"Immediate_Action": "No",
}
]
}
const mapOscarResults = (data) => {
for (let i in Object.keys(data)){
if (Array.isArray(data[Object.keys(data)[i]])){
newKey = data[Object.keys(data)[i]][0]
data = {... data, ...newKey}
delete data[Object.keys(data)[i]]
}
}
return data
};
console.log(mapOscarResults(data))

How to map an array of Object in Javascript

I am stuck with mapping in array of objects.
Please find the below code
const array = [
{
user: "User1",
cities: ["city1", "city2", "city3"],
},
{
user: "User2",
cities: ["city2", "city3", "city4"],
},
];
let x = {};
array.map((item) => {
let user = item.user;
let cities = item.cities;
cities.map((city) => (x[city] = user));
});
Now it returns like this:
const resArray = [{ city1: "User1", city2: "User2", city3: "User2", city4: "User2" }]
I want the array like this:
const resArray = [
{ city1: ["User1"] },
{ city2: ["User1", "User2"] },
{ city3: ["User1", "User2"] },
{ city4: ["User2"] },
];
Can anyone please help me out.
Thanks
Try this
let x = {};
array.forEach((item) => {
item.cities.forEach((city) => {
x[city] = item.cities.includes(city) ? [...x[city] ? x[city] : [], item.user] : [];
});
});
You have been assigning user to city each time. Instead the x[city] should be an array and you should push the new user inside that array.
Try this,
const array = [
{
user: "User1",
cities: ["city1", "city2", "city3"],
},
{
user: "User2",
cities: ["city2", "city3", "city4"],
},
];
let x = {};
array.map((item) => {
let user = item.user;
let cities = item.cities;
cities.map((city) => {
if(x[city] && x[city].length) {
x[city].push(user);
} else{
x[city] = [user];
}
});
});
const res = Object.keys(x).map(key => { return {[key]: x[key]}});
console.log(res);

Firestore bulk add field to array

I am struggling to add a field to an map in an array. I am trying to add "canAssist": false to each map in the array for each of the countries.
Here is my database:
[
{
"Afghanistan": {
"country": "Afghanistan",
"countryCode": "AF",
"countryCodeAlt": "AFG",
"emoji": "🇦🇫",
"packages": [
{
"name": "Luxury Couple",
"cost": "$2000.00",
// I want to add canAssist:false here!
},
{
"name": "Quick Retreat",
"cost": "$1000.00",
// I want to add canAssist:false here!
}
]
}
},
{...}
{...}
]
This is what I've tried:
let travelData = database.collection('countries').doc(docName);
travelData.get()
.then(function(querySnapshot) {
querySnapshot.forEach(function(array) {
packages.map(package => {
return package.add({
canAssist: false
});
})
});
});
You can use Object.values() and object destructuring to achieve this.
const querySnapshot = [
{
Afghanistan: {
country: 'Afghanistan',
countryCode: 'AF',
countryCodeAlt: 'AFG',
emoji: '🇦🇫',
packages: [
{
name: 'Luxury Couple',
cost: '$2000.00',
// I want to add canAssist:false here!
},
{
name: 'Quick Retreat',
cost: '$1000.00',
// I want to add canAssist:false here!
},
],
},
},
{
...
},
{
...
},
];
const updateSnapshot = (snapshot, newData) => {
return snapshot.map(countryData => {
// only one field with the name of the country
const country = Object.values(countryData)[0];
let updatedCountry = { ...country };
const field = country[newData.field];
if (field) {
if (typeof field === 'string') {
updatedCountry[newData.field] = newData.values;
} else if (Array.isArray(field)) {
updatedCountry[newData.field] = field.map(data => ({ ...data, ...newData.values }));
}
}
return { [updatedCountry.country]: updatedCountry };
});
};
(() => {
console.log('Original', JSON.stringify(querySnapshot, null, 4));
const updatedSnapshot = updateSnapshot(querySnapshot, { field: 'packages', values: { canAssist: false } });
console.log('Updated', JSON.stringify(updatedSnapshot, null, 4));
const updatedSnapshot2 = updateSnapshot(querySnapshot, { field: 'emoji', values: '🇪🇸' });
console.log('Spanish!', JSON.stringify(updatedSnapshot2, null, 4));
})();
Of course, you don't need to have that dynamism with the 'newData', I just added in case you want to play around any field of your datasource.

Efficient Way to Iterate and Producing Output in Javascript/React

I have following datas,
let response =[
{
"14714733": [
"Android Testing-1",
"Test special manual",
"Test Manual",
"SECESC"
]
},
{
"10110133": [
"Android Testing-1",
"SECESC"
]
}
]
let shipment =[
{
"masterDocumentNumber": "14714733"
},
{
"masterDocumentNumber": "10110133",
}
]
And
let flagIns=[
{
"fieldValue": "SECESC",
"fieldDescription": "Security Escort"
},
{
"fieldValue": "INS",
"fieldDescription": "Inspection"
}
]
How to iterate and add Corresponding response data in to shipment data as follows,
Desired output
let shipment =[
{
"masterDocumentNumber": "14714733",
"instructions":[
{"index":0,"instruction":"Android Testing-1"},
{"index":1,"instruction":"Test special manual"},
{"index":2,"instruction":"Test Manual"},
{"index":3,"instruction":"Security Escort"}
]
},
{
"masterDocumentNumber": "10110133",
"instructions":[
{"index":0,"instruction":"Android Testing-1"},
{"index":1,"instruction":"Security Escort"}
]
}
]
Note that if flagIns has same data in response then it need to be replaced with it's description.
You should be able to use a function similar to this.. it appears you just need to match up keys and values from the different objects..
function aggregate(response, shipment, flagIns) {
return shipment.map(({ masterDocumentNumber }) => {
let output = { masterDocumentNumber, instructions: [] }
let res = response.find(r => masterDocumentNumber in r);
if (res) {
res[masterDocumentNumber].forEach((r, i) => {
let ins = flagIns.find(fi => fi.fieldValue === r);
output.instructions.push({
index: i,
instruction: ins ? ins.fieldDescription : r
})
})
}
return output;
});
}
const response = [
{
"14714733": [
"Android Testing-1",
"Test special manual",
"Test Manual",
"SECESC"
]
},
{
"10110133": ["Android Testing-1", "SECESC"]
}
];
const shipment = [
{
masterDocumentNumber: "14714733"
},
{
masterDocumentNumber: "10110133"
}
];
const flagIns = [
{
fieldValue: "SECESC",
fieldDescription: "Security Escort"
},
{
fieldValue: "INS",
fieldDescription: "Inspection"
}
];
console.log(aggregate(response, shipment, flagIns));
let shipment =[];
//create array
response.map((res)=>{
//get keys
let key=Object.keys(res)
//loop in instructions
let instructions=[];
res[key].map((val,i)=>{
let inst ={
"index":i,
"instruction":val
}
instructions.push(inst)
})
let m={
"masterDocumentNumber":key,
"instructions":instructions
}
shipment.push(m)
})
console.log(JSON.stringify(shipment))
First flatten the response and flagIns array of objects and then iterate over the shipment array to get the desired output.
let response =[
{
"14714733": [
"Android Testing-1",
"Test special manual",
"Test Manual",
"SECESC"
]
},
{
"10110133": [
"Android Testing-1",
"SECESC"
]
}
]
let shipment =[
{
"masterDocumentNumber": "14714733"
},
{
"masterDocumentNumber": "10110133",
}
]
let flagIns=[
{
"fieldValue": "SECESC",
"fieldDescription": "Security Escort"
},
{
"fieldValue": "INS",
"fieldDescription": "Inspection"
}
]
const responseRes = response.reduce(function (acc, item) {
return Object.assign(acc, item);
}, {});
// responseRes
// {
// '10110133': [ 'Android Testing-1', 'SECESC' ],
// '14714733': [
// 'Android Testing-1',
// 'Test special manual',
// 'Test Manual',
// 'SECESC'
// ]
// }
const flagInsRes = flagIns.reduce(function (acc, item) {
return Object.assign(acc, {
[item.fieldValue]: item.fieldDescription});
}, {});
// flagInsRes
// { SECESC: 'Security Escort', INS: 'Inspection' }
const shipmentRes = shipment.map(obj => {
const temp = {};
temp.masterDocumentNumber = obj.masterDocumentNumber
temp.instructions = responseRes[obj.masterDocumentNumber]
.map((item, index) => {
return {
"index":index,
"instruction":flagInsRes[item] ? flagInsRes[item] : item}
});
return temp;
});
console.log(shipmentRes);

how to map this array if i want to the Names of the groups listed in different "quesytion"

How can I get the names of different activity in an array by using map function in this type of response. So that in a new array, assume that activity[] i will get names of all the activities mention below.
if the array is
const response = [
{
"Groups" : {
"Roles" : {
"submission": {
"subject" : {
"name": "history",
}
}
}
}
}
];
I managed to do this using an IIFE but there may be cleaner ways
assuming there in one object in the array and no other path to other permission
const response = [
{
"Roles" : {
"Permission" : {
"PERMISSION1": {
"Activity" : {
"name": "Manage Clients",
}
},
"PERMISSION2": {
"Activity" : {
"name": "Manage Users",
}
}
}
}
}
];
let activities = (() => {
let res = []
for (let perm in response[0].Roles.Permission) {
for (let act in response[0].Roles.Permission[perm]) {
res.push(response[0].Roles.Permission[perm][act].name)
}
}
return res})()
console.log(activities)
At first, you should convert Permission object to array, cause object doesn't have method map.
Then you could use map function where you can collect all your permissions' names for every item in response
const response = [{
"Roles": {
"Permission": {
"PERMISSION1": {
"Activity": {
"name": "Manage Clients",
}
},
"PERMISSION2": {
"Activity": {
"name": "Manage Users",
}
}
}
}
}];
response.forEach((item) => {
item.Activities = Object.values(item.Roles.Permission).map((permission) => permission.Activity.name)
});
alert(JSON.stringify(response));
The only array you have is response. If each item in response has a Roles that has a Permission that has several keys with objects that have Activity with name then you can do the following:
var response = [
{
Roles: {
Permission: {
PERMISSION1: {
Activity: {
name: 'Manage Clients',
},
},
PERMISSION2: {
Activity: {
name: 'Manage Users',
},
},
},
},
},
];
console.log(
response.map(
(item) =>
Object.values(item.Roles.Permission)
.map(
(permission) => permission.Activity.name
)
)
);
I recommend using a flatMap, so use .reduce.
const response = [{
"Roles": {
"Permission": {
"PERMISSION1": {
"Activity": {
"name": "Manage Clients",
}
},
"PERMISSION2": {
"Activity": {
"name": "Manage Users",
}
}
}
}
}];
const activityNames = response.reduce(function (acc, res) {
const permissions = res.Roles.Permission;
const permissionKeys = Object.keys(permissions);
const names = permissionKeys.map(function(permissionKey) {
return permissions[permissionKey].Activity.name;
});
acc.push(...names);
return acc;
}, [])
console.log(activityNames); // ["Manage Clients", "Manage Users"]

Categories