Creating a map with keys based on values of a different map? - javascript

I'm trying to come up with the .map call that would use a certain field of a dict as key of the result:
input=[ {key:"name", value:"John"}, {key:"city", value:"Chicago"}]
output = input.map( e => **magic here** );
>> output = [ {name:"John"}, {city:"Chicago"}]
I've tried from input.map( e => { e.name:e.value}), to no avail.
Also tried input.map(({key, value}) => ({key:value})), but it does not populate the key value correctly - rather taking "key" as the key of the dicts.
What am I doing wrong here?
Thanks!

You could destructure the object and take computed property name for a new object.
const
input = [{ key: "name", value: "John" }, { key: "city", value: "Chicago" }],
output = input.map(({ key, value }) => ({ [key]: value }));
console.log(output);

Related

How to change an array to a JSON format with javascript

I have an array which is in the below format
node=['ADSss|623', 'sss|635']
I want this to be in a json format as below
[
{
"623": "ADSss"
},
{"635": "sss"
}
]
Is there a simple way to achieve this? it is possible with map function, but i felt it is adding up too many lines of code
Assuming that you array only contain string of format ${value}|${key}, you can map those to an object:
const result = node.map((arrayEl) => {
// Split you array string into value and keys
const [value, key] = arrayEl.split('|');
// return an object key: value
return {[key]: value}
});
console.log(result);
In one line :
const node=['ADSss|623', 'sss|635'];
const json = node.reduce((p, n) => ({ ...p, [n.split('|')[1]]: n.split('|')[0] }), {});
const jsonArray = node.map(n => ({ [n.split('|')[1]]: n.split('|')[0] }));
console.log(json);
console.log(jsonArray);

How to get a single value and value name from an JSON file without knowing the value name

I have a discord bot and it saves achievements in a JSON file. The JSON structure is like this:
{
"784095768305729566": {
"coins": 14598,
"achievements": {
"taking_inventory": true
}
},
}
The command should give you an overview of what achievements you already have.
I want to create an embed and run a for loop for every sub-thing of achievements. If the value is true, the for loop should take the value name and the value and add a field to the embed where the field title is the value name.
I have multiple problems there.
I don't know how to get value names and values. I already tried Object.keys(...) but that gives all keys and not one by one. I don't know how to get the values.
I don't know how to make the for loop as long as all sub-things of achievements.
I tried:
for(var i = 0; i<datafile[id].achievements.length; i++){...}
but that didn't work wither.
You can get an array of an object's entries (keys and values) from Object.entries.
You can filter that array for the value to be true
You can map the result to the key. This gives you an array of achievement keys which had the value "true".
const datafile = {
"784095768305729566": {
"coins": 14598,
"achievements": {
"taking_inventory": true,
"other_achievement": false
}
},
};
const id = "784095768305729566";
const achievements = Object.entries(datafile[id].achievements)
.filter(([k, v]) => v)
.map(([k, v]) => k);
// do something with achievements
console.log(achievements);
You can use Object.entries that returns an array of a given object's own enumerable string-keyed property [key, value] pairs:
let user = "784095768305729566"
let obj = {
"784095768305729566": {
"coins": 14598,
"achievements": {
"taking_inventory": true,
"another_achievement": true,
"yet_another_achievement": false,
"and_one_more": true,
}
},
}
let fields = Object.entries(obj[user].achievements)
.map(([name, value]) => ({
name,
value: value ? '✅' : '❌',
inline: false,
}))
console.log(fields)
// or if you only want to include achievements a user already has
let onlyTruthyFields = Object.entries(obj[user].achievements)
// only where value is truthy
.filter(([name, value]) => value)
.map(([name, value]) => ({
name,
value: '✅',
inline: false,
}))
console.log(onlyTruthyFields)
And then just add these to your embed:
embed.addFields(fields)

How do i make every value of objects in a array as String

I have an array of object something like this
[{id:1, name: "alexander"},{id:2, name: "the great"}]
What is the best way to make the value of all keys as string in the array. So the result should be
[{id:"1", name: "alexander"},{id:"1", name: "the great"}]
Note: My Object is very big and is a combination of number and strings or null and also there is no permanent index of the key in the object. The key in the object can come in any order. Though the key will be at the same place for all the objects. So the desired result should have all the value of all objects in the array as a string.
Use Array.map() to iterate the items. In the map's callback, destructure the objects, extract the id use rest syntax to get the other properties of the object. Convert the id to a string via the String() factory, and then rebuild the object using the spread syntax.
Note: If you expect null or undefined ids, you can use the Nullish coalescing operator (??) to get a default value. For example, String(id ?? '').
const arr = [{id:1, name: "alexander"},{id:2, name: "the great"}]
const result = arr.map(({ id, ...rest }) => ({ id: String(id ?? ''), ...rest }))
console.log(result)
You can use the Array forEach method.
users.forEach(user => user.id = user.id.toString())
where users is the array of objects.
You can try it here:
let users = [{id:1, name: "alexander"},{id:2, name: "the great"}];
users.forEach(user => user.id = user.id.toString());
console.log(users)
You can use map function to iterate each object and save it in each array.
var list = [{ id: "1", name: "alexander" }, { id: "1", name: "the great" }]
var namesValues = list.map((item) => {
return item.name;
});
var idValues = list.map((item) => {
return item.id;
});
console.log(namesValues);
console.log(idValues);

how to create state properties from an array in React?

I am trying to setState of a component from an array of values.
I have these values on filtersSelected array->
["name", "date", "state"]
I want to set these values to my state like this
myState = {
...etc,
name: null,
date: null,
state: null
}
I tried using
this.setState(previousState => ({
...previousState,
...filtersSelected: null
}))
apparently it doesn't work.Can anyone help me?
In order to spread the array into an object you first need to convert the array into an object and then you can spread the object keys into the state:
this.setState((prevState) => ({
...prevState,
...filtersSelected.reduce(function(acc, item) {
return Object.assign(acc, {[item]: null})
}, {});
}))
There are a couple things to note here. First of all, when you call setState, you do not need to provide all of the previous state. setState "merges" the specific state properties that you pass into the already existing state.
It also might be helpful to make your filters selected array an object, as you are trying to use the spread , but is by no means necessary. If you want to keep the array, you can use the code below.
let filtersSelected = ["name", "date", "state"];
this.setState({name: filtersSelected[0], date: filtersSelected[1], state: filtersSelected[2]});
Or, if you make filtersSelected into an object (which I highly recommend), you can do:
let filtersSelected = {name: "name", date: "date", state: "state"};
this.setState(filtersSelected);
Convert your array to object first then use a loop to assign values to your newly created object.
let filteredSelected = ["name", "date", "state"];
let obj;
for(let i of filteredSelected){
obj[i] = null;
}
this.setState(previousState => ({
...previousState,
obj
}))
Everyone has his own way, here are some ways I like
let data = ["name", "date", "state"];
Object.values(data).map(i => this.setState({ [i]: null }))
But I don't like to iterate setState for each element
let data = Object.assign({}, ...["name", "date", "state"].map((prop) => ({[prop]: null})))
this.setState(data)
Or you can do like so
this.setState(["name", "date", "state"].reduce( ( accumulator, currentValue ) => ({...accumulator,[ currentValue ]: null}), {} ));

How to put your object data from a form under specific properties

I have a JSON getting submitted by a form e.g. below.
Var obj1 = {
input1: 'name',
input2: 'surname',
input3: 'email'
}
Now the back-end database has been configured to accept values like this.
FormData: [{
"Key": "input1",
"Value": "Test"
}]
So each value needs to be under key and value, how do I put my input1 and input2 etc under a key and value property for every value in JavaScript? I'm using React but plain JavaScript will do.
var obj1 = {
input1: 'name',
input2: 'surname',
input3: 'email'
}
console.log(Object.keys(obj1).map(Key => ({
Key,
Value: obj1[Key]
})))
Get keys of the object obj1, and then map over it to produce an array of objects.
Try this :
let FormData = Object.keys(obj1).map(key => {
return {"Key" : key, "Value" : obj1[key]}
})

Categories

Resources