In JS I get a response in string ex.
[{"id":"1a869e62-8993-33d0-bd54-f33753044ced","name":"Cubsonx"},{"id":"c534bcba-0096-3668-a34e-a35435e6aafb","name":"Paulina453"}]
And from that I want to only have names, ex.
[{"name":"Cubsonx"},{"name":"Paulina453"}]
and then render every name that is on the list in an discord.js embed fields.
Parse the string to an object:
const jsonObj = '[{"id":"1a869e62-8993-33d0-bd54-f33753044ced","name":"Cubsonx"},{"id":"c534bcba-0096-3668-a34e-a35435e6aafb","name":"Paulina453"}]';
const obj = JSON.parse(jsonObj);
then map the array to the desired one:
const names = obj.map((item) => ({ name: item.name }));
and if you need a string again, then stringify the result:
const stringNames = JSON.stringify(names);
Using _.map from lodash:
const getNames = function(obj) {
return {
name: obj.name
}
}
const data = [{"id":"1a869e62-8993-33d0-bd54-f33753044ced","name":"Cubsonx"},{"id":"c534bcba-0096-3668-a34e-a35435e6aafb","name":"Paulina453"}]
const newArray = _.map(data, getNames)
console.log(newArray) //result: [{"name":"Cubsonx"},{"name":"Paulina453"}]
Using plain JS Array.map MDN: Array.prototype.map
const data = [{"id":"1a869e62-8993-33d0-bd54-f33753044ced","name":"Cubsonx"},{"id":"c534bcba-0096-3668-a34e-a35435e6aafb","name":"Paulina453"}]
const newArray = data.map((item) => ({ name: item.name }))
console.log(newArray) //result: [{"name":"Cubsonx"},{"name":"Paulina453"}]
arr.map((el) => el.name);
This will return an array with names.
Take JSON into obj variable and do
obj.map((element) => element.name)
This will return names
Related
I have an object like this:
const params = {
'userId[]': [1, 2],
'empId': 2,
advance: 'hello',
};
and I want to make a string like this:
userId[]=1&userId[]=2&empId=2&advance=hello
I am trying like this:
const myResult = Object.entries(params)
.map(([key, value]) => {
if (Array.isArray(value)) {
let result;
value.forEach(item => {
`${key}=${value}`
})
return result
}
// return
})
.join('&');
console.log(myResult);
but not able to figure out what to do next.
With a few changes, adding concatenation and non-array values:
const params = {
"userId[]": [1, 2],
empId: 2,
advance: "hello",
}
const myResult = Object.entries(params)
.map(([key, value]) => {
// Assume non-array result as default
let result = `${key}=${value}`
if (Array.isArray(value)) {
// Override for arrays
const r = value
.map((item) => {
return `${key}=${item}`
})
.join("&")
result = r
}
return result
})
.join("&")
console.log(myResult)
URLSearchParams can do most of the work for us, but we still have to handle the array ourselves:
const params = {
'userId[]': [1, 2],
'empId': 2,
advance: 'hello',
};
const p = new URLSearchParams();
for (const [key, value] of Object.entries(params)) {
if (Array.isArray(value)) {
for (const item of value) {
p.append(key, item);
}
} else p.append(key, value);
}
console.log(p.toString());
Looping through the entries of our object, we check if the value is an array. If it isn't we append it, otherwise, we append all its items. URLSearchParams makes the string for us; all we do is tell it what to use for the string :)
Note: "%5b%5D" is the same as "[]" but it's URI encoded. It should be treated the same by the server.
You can do the following instead of iterating over the object:
url = Object.keys(params).map(function(k) {return k + '=' + params[k]}).join('&')"
which would give you
'userId[]=1,2&empId=2&advance=hello'
I think you need this(guessing that you made a typo error)
I have following request body,
{
name1:"john,doe",
name2:"peter,frank"
}
I need to get output as following
{
"name1":["john","doe"],
"name2":["peter","frank"],
}
I am trying to use array methods.
Iterate over the object with for...in, and split the value into an array. Then JSON.stringify the object.
const res = {
name1:"john,doe",
name2:"peter,frank"
};
for (const key in res) {
res[key] = res[key].split(',');
}
console.log(JSON.stringify(res));
You can use Object.entries() and iterate over every key value and convert value into array and get back the new object using Object.fromEntries().
const o = { name1: "john,doe", name2: "peter,frank" },
result = Object.fromEntries(Object
.entries(o)
.map(([key, val]) => ([key, val.split(',')]))
);
console.log(result);
I update an object. This object is an array which can have a length from one to five. This is my object ["max", "dog"].
Now a post method is to be called. It is so if the user has only 2 things filled in, only two things should be sent there. If 5 then 5 (see example for a better explanation.) Does anyone have an idea how best to set this up?
const tag = ["max", "dog"]
const updateInterest = () => {
axios
.post("...", {
first1: max,
first2: dog,
// first3: ...,
// first4: ...,
// first4: ...,
})
.then((res) => {
if (res.status === 200) {
// API update interest
}
})
.catch((error) => {
console.log(error);
});
};
What I try
const tag = ["max", "dog"]
const updateInterest = () => {
const object = "";
tags.map((tag, index) =>{
console.log(tag + " " + index)
object =
`first${index}`: `${tag}`,
})
axios
.post("...", {
object
})
.then((res) => {
if (res.status === 200) {
// API update interest
}
})
.catch((error) => {
console.log(error);
});
};
My loop doesn't really make much sense. How can I add this to an object so that it can be sent in later in an API?
You can use Object.fromEntries() to map an array of arrays to object, like in the following example:
const arr = ["max", "dog"];
const mapped = arr.map((el, i) => [`first${i+1}`, el]);
console.log(Object.fromEntries(mapped))
You can also use Array.prototype.reduce() to achieve the same thing:
const arr = ['cat', 'dog'];
const obj = arr.reduce((acc, cur, i) => ((acc[`first${i + 1}`] = cur), acc), {});
console.log(obj);
Reference: Convert Array to Object
I can't figure out how I can change :
{"first":["de"], "second":["ab","de"], "third":["de"]}
to:
{"de":["first", "second", "third"], "ab":["second"]}
I want to associate unique values with list of containing keys. What I tried(but I think I'm far from it):
const data = {
"first":["de"],
"second":["ab","de"],
"third":["de"]
}
console.log(
Object
.keys(data).reduce(function(obj, key) {
obj[data[key]] = key;
return obj;
}, {})
)
Thanks for your help!
Object.entries to get it into an array, reduce to build the new object, and forEach to loop over the array
const o = {"first":["de"], "second":["ab","de"], "third":["de"]}
const result = Object.entries(o).reduce((obj, [key, arr])=>{
arr.forEach(lng => {
obj[lng] = obj[lng] || [];
obj[lng].push(key);
})
return obj
}, {});
console.log(result);
You have to loop the array and for each item in the array check if an array for that value exists in the accumulator or not before adding it:
let result = Object.entries(data).reduce((acc, [key, arr]) => { // for each key-array of the original object
arr.forEach(value => { // for each value in the array
acc[value] = acc[value] || []; // create an array in the output object if it doesn't already exist
acc[value].push(key); // push the key to it
});
return acc;
}, {});
I also used Object.entries with each entry desctuctured as [key, arr] so I don't have to use the extra [key] to get the array while using Object.keys.
Demo:
let data = {"first":["de"], "second":["ab","de"], "third":["de"]};
let result = Object.entries(data).reduce((acc, [key, arr]) => {
arr.forEach(value => {
acc[value] = acc[value] || [];
acc[value].push(key);
});
return acc;
}, {});
console.log(result);
On reduce callback, data[key] is an array of string values. So it is needed to loop that data[key] array values and assign value for each array item.
const data = {
"first":["de"],
"second":["ab","de"],
"third":["de"]
}
console.log(
Object.keys(data).reduce(function(obj, key) {
data[key].forEach((val) => {
obj[val] ? obj[val].push(key) : obj[val] = [ key ];
});
return obj;
}, {})
)
Try this (naive solution), if this works for you
const data = { first: ["de"], second: ["ab", "de"], third: ["de"] };
let dataMap = new Map();
Object.keys(data).forEach((key) => {
data[key].forEach((val) => {
if (dataMap.has(val)) {
dataMap.set(val, [...dataMap.get(val), key]);
} else {
dataMap.set(val, [key]);
}
});
});
let nData = [];
dataMap.forEach((value, key) => {
nData.push({
[key]: value
});
});
console.log(nData);
You could take a double reduce with the entries.
const
data = { first: ["de"], second: ["ab", "de"], third: ["de"] },
result = Object
.entries(data)
.reduce((o, [value, keys]) => keys.reduce((q, key) => {
(q[key] ??= []).push(value);
return q;
}, o), {});
console.log(result);
I'm not using reduce but here's a "bruteforce" for your problem which works:
res = {};
Object.keys(data).forEach(key => {
data[key].forEach(el => {
if (! res[el])
res[el] = [];
if (! res[el].includes(key))
res[el].push(key);
})
});
This question already has answers here:
How do I convert array of Objects into one Object in JavaScript?
(17 answers)
Closed 3 years ago.
I have an array like this:
array = [{profile: 'pippo'}, {profile: 'mickey'}]
and I would like to transform it to this:
object = {0: 'pippo', 1: 'mickey'}
You can use a short reduce:
const array = [{profile: 'pippo'}, {profile: 'mickey'}]
const output = array.reduce((a, o, i) => (a[i] = o.profile, a), {})
console.log(output)
Or even use Object.assign:
const array = [{profile: 'pippo'}, {profile: 'mickey'}]
const output = Object.assign({}, array.map(o => o.profile))
console.log(output)
However, your output is in the same format as an array, so you could just use map and access the elements by index (it really just depends on the use case):
const array = [{profile: 'pippo'}, {profile: 'mickey'}]
const output = array.map(o => o.profile)
console.log(output)
Extract the profiles value with Array.map() and spread into an object:
const array = [{profile: 'pippo'}, {profile: 'mickey'}]
const result = { ...array.map(o => o.profile) }
console.log(result)
using reduce it would be very easy. there you have how it works and a working example.
array = [{
profile: 'pippo'
}, {
profile: 'mickey'
}]
const finalObj = array.reduce((accum, cv, index) => {
accum[index] = cv['profile']
return accum;
}, {})
console.log(finalObj)