Spread Operator for array of array - javascript

How to perform spread opration on salesuser array object. need to add ..salesuserstargetAmount:500, in that object
{
"station": [
{
"stationname":"chennai",
"stationtargetAmount":500,
"salesusers":[
{
" salesusersname":"tester",
},
]
},
{
"stationname":"chennai22222",
"stationtargetAmount":500,
"salesusers":[
{
" salesusersname":"tester222222",
},
]
}
]
}
Tried with
let salesusertargetamt = "100"
this.setState({
salesusers: this.state.station.map((items) => {
items.salesusers.map(el => (el.salesusersname !== "" ? { ...el, salesusertargetamt } : el))
});

Curly braces ({) are tricky here because they both mean block of code and JavaScript object so you need to wrap them with ():
let salesusertargetamt = "100";
let obj = {
"station": [
{
"stationname":"chennai",
"stationtargetAmount":500,
"salesusers":[
{
" salesusersname":"tester",
},
]
},
{
"stationname":"chennai22222",
"stationtargetAmount":500,
"salesusers":[
{
" salesusersname":"tester222222",
},
]
}
]
};
let result = obj.station.map(items => ({
...items,
salesusers: items.salesusers.map(user => (user.salesusersname !== "" ? {...user, salesusertargetamt} : user ))
}))
console.log(result);

let salesusertargetamt = "100"
this.setState({
salesusers: this.state.station.map((items) => {
return items.salesusers.map(el => (el.salesusersname !== "" ? { ...el, stationtargetAmount: salesusertargetamt } : el))
});

Related

Search multiple elements by key inside multiple json structures

I need to get the values of all the the arrays matching the items key. I'm making a script in Javascript that needs to read the objects inside multiple items arrays in multiple json files, but each json has a different structure. Example:
file1.json:
{
"name":"First file",
"randomName3874":{
"items":[
{
"name":"item1"
}
]
},
"items":[
{
"name":"randomItem2"
}
]
}
file2.json
{
"name":"Another file",
"randomName00000":{
"nestedItems":{
"items":[
{
"name":"item87"
}
]
}
},
"stuff":{
"items":[
{
"name":"randomItem35"
}
]
}
}
Desired result:
{
"data":[
{
"items":[
{
"name":"item1"
}
]
},
{
"items":[
{
"name":"randomItem2"
}
]
},
{
"items":[
{
"name":"item87"
}
]
},
{
"items":[
{
"name":"randomItem35"
}
]
}
]
}
In both files I want to extract the arrays that have the key items. In the examples above the script should find 4 arrays. As you can see in both files each array is nested differently. How can I make this using Javascript?
This will do it:
function omit(key, obj) {
const { [key]: omitted, ...rest } = obj;
return rest;
}
function getItems(obj) {
return (typeof obj === 'object'
? 'items' in obj
? [{ items: obj.items }].concat(getItems(omit('items', obj)))
: Object.values(obj).map(v => getItems(v))
: []
).flat()
}
console.log({
data: [file1, file2].map(o => getItems(o)).flat()
})
See it working:
const file1 = {
"name":"First file",
"randomName3874":{
"items":[
{
"name":"item1"
}
]
},
"items":[
{
"name":"randomItem2"
}
]
}
const file2 = {
"name":"Another file",
"randomName00000":{
"nestedItems":{
"items":[
{
"name":"item87"
}
]
}
},
"stuff":{
"items":[
{
"name":"randomItem35"
}
]
}
}
function omit(key, obj) {
const { [key]: omitted, ...rest } = obj;
return rest;
}
function getItems(obj) {
return (typeof obj === 'object'
? 'items' in obj
? [{ items: obj.items }].concat(getItems(omit('items', obj)))
: Object.values(obj).map(v => getItems(v))
: []
).flat()
}
console.log({
data: [file1, file2].map(o => getItems(o)).flat()
})
Let's take it a step further and make it generic (work with an array of objects and extract any key) and provide it as a function, which you can use in other projects, as well:
function extractKey(objects, key) {
const omit = (key, obj) => {
const { [key]: omitted, ...rest } = obj;
return rest;
}
const getValues = (obj) => (typeof obj === 'object'
? key in obj
? [{ [key]: obj[key] }].concat(getValues(omit(key, obj)))
: Object.values(obj).map(o => getValues(o))
: []
).flat();
return objects.map(o => getValues(o)).flat()
}
// use:
extractKey([file1, file2], 'items');
See it working:
function extractKey(objects, key) {
const omit = (key, obj) => {
const { [key]: omitted, ...rest } = obj;
return rest;
}
const getValues = (obj) => (typeof obj === 'object'
? key in obj
? [{ [key]: obj[key] }].concat(getValues(omit(key, obj)))
: Object.values(obj).map(o => getValues(o))
: []
).flat();
return objects.map(o => getValues(o)).flat()
}
// test:
const file1 = {
"name":"First file",
"randomName3874":{
"items":[
{
"name":"item1"
}
]
},
"items":[
{
"name":"randomItem2"
}
]
}
const file2 = {
"name":"Another file",
"randomName00000":{
"nestedItems":{
"items":[
{
"name":"item87"
}
]
}
},
"stuff":{
"items":[
{
"name":"randomItem35"
}
]
}
}
console.log(
{ data: extractKey([file1, file2], 'items') }
)
Looping over like a tree-nested loop should do it.
let file1 = {
"name": "First file",
"randomName3874": {
"items": [
{
"name": "item1"
}
]
},
"items": [
{
"name": "randomItem2"
}
]
}
let file2 = {
"name": "Another file",
"randomName00000": {
"nestedItems": {
"items": [
{
"name": "item87"
}
]
}
},
"stuff": {
"items": [
{
"name": "randomItem35"
}
]
}
}
let itemsValues = [];
let desiredKey = 'items'
let loop = (value) => {
if (Array.isArray(value)) {
value.forEach(loop);
} else if (typeof value === 'object' && value !== null) {
Object.entries(value).forEach(([key, val]) => (key === desiredKey) ? itemsValues.push({ [desiredKey]: val }) : loop(val));
}
}
loop(file1);
loop(file2);
console.log(itemsValues);
This should work:
function getIdInObjects(id, objects, output = { data: [] }) {
if (id in objects) output.data.push({[id]: objects[id]});
for (const key in objects) {
if (typeof(objects[key]) === 'object') getIdInObjects(id, objects[key], output);
}
return output;
}
console.log('items', [object1, object2])

JavaScript Array attribute change

I have an array like this.
let arr = [
{
"ABBRIVATION":"ISB",
"name":"ISLAMABAD",
},
{
"ABBRIVATION":"RAW",
"name":"PINDI",
},
{
"ABBRIVATION":"SWB",
"name":"SWABI",
},
{
"ABBRIVATION":"AQ",
"name":"AQEEL",
},
]
I want to change it to like this
let me explain it a little. I want to assign the abbreviation directly to the name and the iterate through that array
let outout = [
{
"ISB":"ISLAMABAD"
},
{
"RAW":"ISLAMABAD"
},
{
"SWB":"SWABI"
},
{
"AQ":"AQEEL"
},
]
that is what I tried
let k = arr.map((item) => {
return item.ABB = item.name
})
console.log(k)
and here is the output
[ 'ISLAMABAD', 'PINDI', 'SWABI', 'AQEEL' ]
Here you go, use array map, simples
let arr = [
{
"ABBRIVATION":"ISB",
"name":"ISLAMABAD",
},
{
"ABBRIVATION":"RAW",
"name":"PINDI",
},
{
"ABBRIVATION":"SWB",
"name":"SWABI",
},
{
"ABBRIVATION":"AQ",
"name":"AQEEL",
},
]
let outout = arr.map(({ABBRIVATION, name}) => ({[ABBRIVATION]: name}));
console.log(outout);
Nothing more than a simple Array.prototype.map() needed.
let arr = [
{
ABBRIVATION: "ISB",
name: "ISLAMABAD",
},
{
ABBRIVATION: "RAW",
name: "PINDI",
},
{
ABBRIVATION: "SWB",
name: "SWABI",
},
{
ABBRIVATION: "AQ",
name: "AQEEL",
},
];
const result = arr.map(e => ({ [e.ABBRIVATION]: e.name }));
console.log(result);
map over the array of objects (map returns a new array) and assign the name to a new key defined by the abbreviation.
You code works the way it does because item.ABB is undefined, but you're also assigning item.name to it which does get returned, so you just get an array of names returned.
const arr=[{ABBRIVATION:"ISB",name:"ISLAMABAD"},{ABBRIVATION:"RAW",name:"PINDI"},{ABBRIVATION:"SWB",name:"SWABI"},{ABBRIVATION:"AQ",name:"AQEEL"}];
const out = arr.map(obj => {
return { [obj.ABBRIVATION]: obj.name };
});
console.log(out);
Hi I have seen people answer, but most of them use the map function, I provide some other solutions, hoping to expand the thinking
Use forEach function
const datas = [
{
"ABBRIVATION":"ISB",
"name":"ISLAMABAD",
},
{
"ABBRIVATION":"RAW",
"name":"PINDI",
},
{
"ABBRIVATION":"SWB",
"name":"SWABI",
},
{
"ABBRIVATION":"AQ",
"name":"AQEEL",
}
];
datas.forEach((obj, i, arr) => {
const{'ABBRIVATION':k, 'name':v} = obj;
arr[i] = {[k]:v};
});
console.log(datas);
Use flatMap function
const datas = [
{
"ABBRIVATION":"ISB",
"name":"ISLAMABAD",
},
{
"ABBRIVATION":"RAW",
"name":"PINDI",
},
{
"ABBRIVATION":"SWB",
"name":"SWABI",
},
{
"ABBRIVATION":"AQ",
"name":"AQEEL",
}
];
const result = datas.flatMap(obj => {
const {'ABBRIVATION':k, 'name':v} = obj;
return {[k]:v};
});
console.log(result);
this is how you suppose to do it.
arr.reduce((d, c)=>([...d, {[c.ABBRIVATION]: c.name}]),[])
let arr = [
{
"ABBRIVATION":"ISB",
"name":"ISLAMABAD",
},
{
"ABBRIVATION":"RAW",
"name":"PINDI",
},
{
"ABBRIVATION":"SWB",
"name":"SWABI",
},
{
"ABBRIVATION":"AQ",
"name":"AQEEL",
},
]
console.log(arr.reduce((data, current)=>([...data, {[current.ABBRIVATION]: current.name}]),[]))

Javascript: merge cartesian array of objects

I have below array of objects
{
"roleid":[{"rolename":[1639]}],
"modnameid":[{"mname":[1516,1515,1514]}],
"accesstype":[{"accesstype":["VO","AA"]}]
}
and I want to convert it format below
[
{"modnameid":1516,"accesstype":"VO","roleid":1639},
{"modnameid":1516,"accesstype":"AA","roleid":1639},
{"modnameid":1515,"accesstype":"VO","roleid":1639},
{"modnameid":1515,"accesstype":"AA","roleid":1639},
{"modnameid":1514,"accesstype":"VO","roleid":1639},
{"modnameid":1514,"accesstype":"AA","roleid":1639}
]
How do we go about it, basic assumption what multi-tier map based operation, food for thoughts
Assistance is appreciated!
Beside the hardcoded answer, you could take a dynamic approach and get first an object with flat arrays of data and build an array of the cartesian product.
function getCartesian(object) {
return Object.entries(object).reduce((r, [k, v]) => {
var temp = [];
r.forEach(s =>
(Array.isArray(v) ? v : [v]).forEach(w =>
(w && typeof w === 'object' ? getCartesian(w) : [w]).forEach(x =>
temp.push(Object.assign({}, s, { [k]: x }))
)
)
);
return temp;
}, [{}]);
}
const
data = { roleid: [{ rolename: [1639] }], modnameid: [{ mname: [1516, 1515, 1514] }], accesstype: [{ accesstype: ["VO", "AA"] }] },
flat = v => v && typeof v === 'object'
? Object.values(v).flatMap(flat)
: v;
temp = Object.fromEntries(Object.entries(data).map(([k, v]) => [k, flat(v)]));
console.log(temp);
console.log(getCartesian(temp));
.as-console-wrapper { max-height: 100% !important; top: 0; }
can user
let data = {
"roleid": [{ "rolename": [1639] }],
"modnameid": [{ "mname": [1516, 1515, 1514] }],
"accesstype": [{ "accesstype": ["VO", "AA"] }]
}
let roles = []
data.roleid.forEach(element => {
roles = [...roles, ...element.rolename]
});
let names = []
data.modnameid.forEach(element => {
names = [...names, ...element.mname]
});
let types = []
data.accesstype.forEach(element => {
types = [...types, ...element.accesstype]
});
let informations = []
roles.forEach(role => {
names.forEach(name => {
types.forEach(type => {
informations.push({ "modnameid": role, "accesstype": type, "roleid": name })
});
});
});
console.log(informations);

how to change the nest array object key and same array in javascript

I have two arrays of an object obj and editObj I am trying the change the inner array key value from obj array-based on editObj.
const obj= [
{
"id":"cmate",
"permissions":[
{
"name":"audioFeature",
"description":"sample description",
"options":[{"name":"Yes","value":"Y"}, {"name":"No","value":"N"}, {"name":"Veiw","value":"V"}],
},
{
"name":"documentFeature",
"description":"sample description",
"options":[{"name":"Yes","value":"Y"},{"name":"No","value":"N"}],
}
]
},
{
"id":"Vmate",
"permissions":[
{
"name":"audioFeature",
"description":"sample description",
"options":[{ "name":"Yes", "value":"Y"},{"name":"No", "value":"N"}],
},
{
"name":"videoFeature",
"description":"sample description",
"options":[{ "name":"Yes", "value":"Y"},{"name":"No","value":"N"}],
}
]
}
] ;
const editObj = [
{
"id":"cmate",
"attributes":[
{
"name":"audioFeature",
"value":["Y",N"],
"disabled":true
},
{
"name":"documentFeature",
"value":["N"],
"disabled":false
}
]
},
{
"id":"Vmate",
"attributes":[
{
"name":"audioFeature",
"value":["Y","N"],
"disabled":false
},
{
"name":"videoFeature",
"value":["Y","N"],
"disabled":true
}
]
}
]
I had tried with this code but I stuck in a certain time I try to return the resultArr but it's not working for me.
obj.map(el => {
editObj.map(elm => {
if (el.applicationId === elm.applicationId) {
el.permissions.map(p => {
elm.attributes.map(a => {
if(p.name === a.name) {
console.log(el)
const resultArr = el.permissions.map((item, index) => {
let res = { ... item };
res.options = item.options.filter(option => elm[0].attributes[index].value.includes(option.value));
return res;
});
console.log(resultArr)
}
})
})
}
})
})
my expected output should be
[
{
"id":"cmate",
"permissions":[
{
"name":"audioFeature",
"description":"sample description",
"options":[{"name":"Yes","value":"Y"}, {"name":"No","value":"N"}],
"disabled":true
},
{
"name":"documentFeature",
"description":"sample description",
"options":[{"name":"No","value":"N"}],
"disabled":false
}
]
},
{
"id":"Vmate",
"permissions":[
{
"name":"audioFeature",
"description":"sample description",
"options":[{ "name":"Yes", "value":"Y"},{"name":"No", "value":"N"}],
"disabled":false
},
{
"name":"videoFeature",
"description":"sample description",
"options":[{ "name":"Yes", "value":"Y"},{"name":"No","value":"N"}],
"disabled":true
}
]
}
]
Try this piece of code, it will take obj and editObj and return the output in outputObj.
const outputObj = [];
obj.forEach(el => {
editObj.forEach(elm => {
if (el.id === elm.id) {
let tempObj = {
id: el.id,
permissions:[]
}
el.permissions.forEach(p => {
elm.attributes.forEach(a => {
if (p.name === a.name) {
const rObj = {
name: p.name,
description: p.description,
disabled: a.disabled,
options: p.options.filter(option => {
if(a.value.includes(option.value)) {
return option
}
})
}
tempObj.permissions.push(rObj)
}
})
})
outputObj.push(tempObj);
}
})
})
I changed your code a little bit and it start showing something:
You need to explicitly return from arrow function.
console.log(obj.map(el => {
return editObj.map(elm => {
if (el.id === elm.id) {
return el.permissions.map(p => {
return elm.attributes.map(a => {
if(p.name === a.name) {
return resultArr = el.permissions.map((item, index) => {
let res = { ... item };
res.options = item.options.filter(option => elm.attributes[index].value.includes(option.value));
return res;
});
}
})
})
}
})
}));
Checkout an interesting article to understand your mistake:
https://dev.to/samanthaming/es6-arrow-functions-cheatsheet-1cn#:~:text=With%20normal%20functions%2C%20if%20you,return%20keyword%20can%20be%20skipped.

how to change value of all nodes of json array

I have a json array with different key values and need to add a ServerUrl to the beginning of all node values using a loop without writing multiple statements to do that by using javascript:
"Urls": [
{ "getCar": "/getAllCars" },
{ "getPerson": "/getAllPersons" },
{ "getBook": "/getAllBooks" }
],
"ServerUrl": "http://192.168.1.1:3000"
The expected result must be:
"Urls": [
{ "getCar": "http://192.168.1.1:3000/getAllCars" },
{ "getPerson": "http://192.168.1.1:3000/getAllPersons" },
{ "getBook": "http://192.168.1.1:3000/getAllBooks" }
],
Any advice would be appreciated.
You can use map to map your objects to new objects. Those objects have a single property, which you can get with Object.keys. The new object can get that same property name using the computed property name feature:
var obj = {
"Urls": [
{ "getCar": "/getAllCars" },
{ "getPerson": "/getAllPersons" },
{ "getBook": "/getAllBooks" }
],
"ServerUrl": "http://192.168.1.1:3000"
};
var urls = obj.Urls.map(o => Object.keys(o).map(k => ({ [k]: obj.ServerUrl + o[k] }))[0]);
console.log(urls);
const jsonVal = {
"Urls": [
{ "getCar": "/getAllCars" },
{ "getPerson": "/getAllPersons" },
{ "getBook": "/getAllBooks" }
],
"ServerUrl": "http://192.168.1.1:3000"
}
const result = jsonVal.Urls.map(val =>
Object.keys(val).reduce((resultObj, endpointKey) => {
resultObj[endpointKey] = `${jsonVal.ServerUrl}${val[endpointKey]}`;
return resultObj;
}, {})
);
Try (where your data are in d)
d.Urls.forEach( (x,i,a,k=Object.keys(x)[0]) => x[k] = d.ServerUrl + x[k]);
let d = {
"Urls": [
{ "getCar": "/GetAllGroupCustomers" },
{ "getPerson": "/getAllItems" },
{ "getBook": "/GetAllCustomers" }
],
"ServerUrl": "http://192.168.1.1:3000"
}
d.Urls.forEach( (x,i,a,k=Object.keys(x)[0]) => x[k] = d.ServerUrl + x[k]);
console.log(d);
A version that modifies your own object
var obj = {
"Urls": [
{ "getCar": "/getAllCars" },
{ "getPerson": "/getAllPersons" },
{ "getBook": "/getAllBooks" }
],
"ServerUrl": "http://192.168.1.1:3000"
};
obj.Urls.forEach(o => o[Object.keys(o)[0]] = `${obj.ServerUrl}${o[Object.keys(o)[0]]}`);
console.log(obj);

Categories

Resources