allInfo.map((name) => console.log("arr", name.firstName))
The above statement is an array. I want to iterate the values and put them in the following array to show it in the dropdown.
const info = [
{ value: "firstName", label: "firstName" },
{ value: "first",label: "first"},
{ value: "lastName", label: "lastName" }
]
I want to iterate the value of allInfo and put it inside the value of info. Instead of value = "firstName", I want to get it from the allInfo array. Can anyone help me with this?
Just map the allInfo array directly to get the info array.
const info = allInfo.map(name => ({
value: name.firstName,
label: name.firstName,
}));
If you want to have some static values in the info array too, you can use the spread operator like this:
const allInfoItems = allInfo.map(name => ({
value: name.firstName,
label: name.firstName,
}));
const info = [
{ value: 'something', label: 'something' },
...allInfoItems
]
Related
I have the data of the array object in a variable called hi[0].child.
hi[0].child = [
{code: "food", name: "buger"},
{code: "cloth", name: "outher"},
{code: "fruit", name: "apple"},
]
What I want to do is create a variable called hello, change the key value of hi[0].child, and put it in the hello variable.
For example, the key value of code is changed to value and name is changed to label. The values I want are as below.
expecter answer
hello = [
{label: "burger", value: "food"},
{label: "outher", value: "cloth"},
{label: "apple", value: "fruit"},
]
But when I use my code I get these errors.
Did not expect a type annotation here
so How can i fix my code?
this is my code
let hello = []
hi[0].child.map((v) => {
hello.push(label: v.name, value: v.code)
})
You've missed the curly brackets for the object, it should be hello.push({ label: v.name, value: v.code }).
Also, map is not the right method to be used here, use forEach instead or use the value returned from map (as shown below).
const data = [
{ code: "food", name: "buger" },
{ code: "cloth", name: "outher" },
{ code: "fruit", name: "apple" },
];
const updatedData = data.map((v) => ({ label: v.code, value: v.name }));
console.log(updatedData);
Change the code like this
let hello = []
hi[0].child.map((v) => {
hello.push({label: v.name, value: v.code})
})
You need to pass object
I have a js file that is just a an array with the name and type of person. I am trying to write a function in my other file to iterate through that array of objects and return just the object that matches a certain criteria. Here is my code.
person.js
export const persons_options = [
{
name: 'Andrew',
type: 'Athlete',
},
{
name: 'Paul',
type: 'Worker',
},
{
name: 'Phil',
type: 'Developer',
},
]
utils.js
// params initialized already
person_type = params.subType
const name = persons_options.map((option) => {
if(person_type === option.type){
return option.name
}
})
const person = name
The issue is I know map creates a new array so the output is ,,Phil. How would I just return one of the object names instead of all of them.
find() will do the work
let persons_options = [
{
name: 'Andrew',
type: 'Athlete',
},
{
name: 'Paul',
type: 'Worker',
},
{
name: 'Phil',
type: 'Developer',
},
]
let obj = persons_options.find(o => o.type === 'Developer');
//to return name
console.log("name",obj.name);
console.log(obj);
You need to use the find function.
See here the list of functions that you can call on an array:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#instance_methods
filter might best suit your case if multiple results may be returned.
I have two arrays
arrayOfItems: [
{
id: '4321-3321-4423',
value: 'some text'
},
{
id: '4322-4654-9875',
value: 'some text again'
}
]
Then the second array
itemX: [
{
id: '3214-6543-4321',
nestedArrayOfItems:[
{id: '4321-3321-4423'}
{id: '3455-8765-7764'}
]
}
]
I need to create a new array based on arrayOfItems that doesn't include any of the id's in the itemX.nestedArrayOfItems
Because of it being a nested Array I'm drawing a blank on what I need to do... I'm searching through Lodash to see if there is something that doesn't involve me using a bunch of for loops.
You can use Array.prototype.filter() and then check if the id exists with
Array.prototype.some() like so:
const arrayOfItems = [
{
id: '4321-3321-4423',
value: 'some text'
},
{
id: '4322-4654-9875',
value: 'some text again'
}
]
const itemX = [
{
id: '3214-6543-4321',
nestedArrayOfItems: [
{id: '4321-3321-4423'},
{id: '3455-8765-7764'}
]
}
]
const res = arrayOfItems.filter(item => !itemX[0].nestedArrayOfItems.some(({ id }) => id === item.id))
console.log(res);
how about this :
let difference = arrayOfItems.filter(x => ! itemX.nestedArrayOfItems.includes(x));
PS : ids must be string
So I've been stumped on this for hours and I can't really figure out an elegant solution to solve this problem. Let's say I have this:
let Fields = {
GAME: [
{ code: '{{GTAV}}', title: { en: "grnti"} },
{ code: '{{GTA5}}', title: { en: "Grand theph " } },
]
};
How can I turn this into a new format that looks like this ?
let Fields = {
tags: [
{ name: 'GAME', tags:[
{ name: 'grnti', value: "{{GTAV}}" },
{ name: 'Grand theph', value: "{{GTA5N}}" }
]},
]};
I tried to create a function to do the job , but for some reason my brain cannot seem to grasp the solution. Any help please !
A simple version of this might look like the following:
const transform = (fields) => ({
mergeTags: Object .entries (fields) .map (([name, innerFields]) => ({
name,
mergeTags: innerFields .map (({code, title: {en}}) => ({name: en, value: code}))
}))
})
const fields = {RECIPIENT: [{code: '{{RECIPIENT.LN}}', title: {en: "name"}}, {code: '{{RECIPIENT.FN}}', title: {en: "first name" }}]}
console .log (transform (fields))
But from your nested mergeTags properties, I'm guessing that there is something recursive going on. If so, we need more information about the input and output structures.
i just threw a nested reduce function together.
const transformed = Object.entries(Fields).reduce((tags, [key, value]) => {
const mergedTags = value.reduce((codes, code) => {
codes.mergeTags.push({name: code.title.en, value: code.code});
return codes;
}, {name: key, mergeTags: []})
tags.mergeTags.push(mergedTags)
return tags;
}, {mergeTags: []})
Does that work for you?
It is hard to tell exactly from your question what you are hoping to accomplish as well as the shape of your data. Based on your question though, you would probably want to use the Object.keys and map functions
let Fields = {
RECIPIENT: [
{ code: '{{RECIPIENT.LN}}', title: { en: "name" } },
{ code: '{{RECIPIENT.FN}}', title: { en: "first name" } },
]
};
// gets the keys of the 'Fields' object(in this case only 'RECIPIENT'
let newFields = Object.keys(Fields)
// each key should create a new object with the 'key' from the original object as the 'name' of the new object
.map(key => ({
name: key,
// 'Fields[key]' gets the array from the 'RECIPIENT' property and then creates a new object from each object in the original array, mapping the 'title.en' property in the original object to 'name' in the new object and 'code' in the original object to 'value' in the new object
mergeTags: Fields[key].map(property => ({
name: property.title.en,
value: property.code
}))
}));
console.log(newFields);
Here's a clean way that may seem a bit like magic, but I'll walk you through what's going on.
let Fields = {
RECIPIENT: [
{ code: '{{RECIPIENT.LN}}', title: { en: "name"} },
{ code: '{{RECIPIENT.FN}}', title: { en: "first name" } },
]
};
const { pipe, fork, map, get } = rubico
const Transformed = pipe([
Object.entries, // { RECIPIENT: [...] } => [['RECIPIENT', [...]]
fork({
mergeTags: map(fork({ // iterate through each entry ['RECIPIENT', [...]]
name: get(0), // name is the item at index 0 of each entry
mergeTags: pipe([
get(1), // mergeTags starts with index 1 of each entry, the array of code+title objects
map(fork({ // iterate through the array of code + title objects and create new objects
name: get('title.en'), // name is title.en of each object
value: get('code'), // value is title.code of each object
})),
]),
})),
}),
])(Fields)
console.log(JSON.stringify(Transformed, null, 2))
<script src="https://unpkg.com/rubico"></script>
Disclaimer: I am the author of rubico
You can examine these methods in depth at the documentation
I'm learning to manipulate JSON data and I am stuck trying to figure out how to cajole the following JSON into what I want as shown below:
Any pointers to function/terms/concepts that I should learn for this sort of problem would be greatly appreciated! Thanks
JSON object
{
car: 1,
van: 5,
cat: 99999999999999999999999
}
Desired outcome:
items: [
{ "type": "car", "value": "1"},
{ "type": "van", "value": "5"},
{ "type": "cat", "value": "99999999999999999999999"}
]
You can use a combination of Object.entries and Array.prototype.map:
const obj = { car: 1, van: 5, cat: 99999999999999999999999 };
let list = Object.entries(obj) // [["car",1],["van",5],["cat",99999999999999999999999]]
.map(x => ({ type: x[0], value: x[1] }));
console.log(list);
Or, with some destructuring:
const obj = { car: 1, van: 5, cat: 99999999999999999999999 };
let list = Object.entries(obj)
.map(([type, value]) => ({ type, value }));
console.log(list);
The callback to map:
([type, value]) => ({ type, value })
Expects an array as parameter: [type, value]. The first value in that array is assigned to type, the second one to value.
Then we use a shorthand form to set these values in our returned object:
=> ({ type, value })
I'm a beginner. I tried to solve the problem and this is the best I can come up with, tested in Node.js 10.
const obj = {"car": 1, "van": 5, "cat": 999999}
const items = []
for (let key in obj) {
items.push({"type": key, "value": obj[key]})
}
console.log(items)
One thing I am slightly confused about is the difference between for..in vs for..of, I'm currently looking into it.
Object.keys will return:
['car', 'van', 'cat'];
On this array you can use Array's map function which creates a new array with the results of calling a provided function on every element in the calling array.
var a = {
car: 1,
van: 5,
cat: 99999999999999999999999
}
m = Object.keys(a).map((v)=>{
return {
type: v,
value: a[v]
}
})
console.log(m);
#GustavMahler hope you understand. To learn more about array functions you should look map, reduce and filter.
This one uses object.keys
let js = {car:1, van:5, cat:9999}
Object.keys(js).map( x => ({type: x, value: js[x] }) )
[ { type: 'car', value: 1 },
{ type: 'van', value: 5 },
{ type: 'cat', value: 9999 } ]