I am new to typescript. please help to push the data so here it goes
Here the story goes I have string array and i need to push it to the json object
interface LocalIds {
value: string;
label: string;
}
const localIds = [
{ value: 'test', label: 'test' },
{ value: 'test2', label: 'test2' },
];
////////////// HERE in string array that data is coming ///////////
const localIdentifiers: string[] = result.data.map((item: string) => item);
///////////// I want to push the string array data to json object with label & value//////
// I experimented alot but giving some type error and all I am not getting
localIds.push({ label: 'abc', value: 'abc' });
localIdentifiers.map(i => localIds.push(...localIds:{value:i,label:i}[])); //ERROR
Half of your code does nothing useful
result.data.map((item: string) => item) will do nothing
using map when not returning anything inside it is pointless. At very least use forEach instead. or even better....
You should use map with concat:
interface LocalIds {
value: string;
label: string;
}
const localIds = [
{ value: 'test', label: 'test' },
{ value: 'test2', label: 'test2' },
];
localIds.push({ label: 'abc', value: 'abc' });
const finalLocalIds = localIds.concat( result.data.map((i: string) => ({value:i,label:i})) );
Live example
Try fixing last line as following
replace ; with , and remove [] at the end
localIdentifiers.map(i => localIds.push(...localIds, {value:i,label:i}));
also, you dont need ...localIds, since it will duplicate current array every time element is pushed to array
Related
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.
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
]
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 have a Rest API which returns data in json of the form :
["1.6.3","1.6.4","1.6.5","1.6.6","1.7.0","1.7.2"]
I need the data in this format:
var options = [{ value: 'one', label: 'One' }, { value: 'two', label: 'Two', clearableValue: false }
];
After fetching the data I am using the following code to map the data in the required format:
if (this.state.coreversions) {
var options = [
this.state.coreversions.map(versions =>
`{ value: '${versions}', label: '${versions}' },`
)
];
}
Here the variable version is equal to a single value of the data returned by the Rest API
Any help would be appreciated.
Array#map returns an array, therefore you do not have to enclose it within square brackets.
Amend your code as follows:
if (this.state.coreversions) {
var options = this.state.coreversions.map(
versions => ({value: versions, label: versions})
);
}
// simplified this.state.coreversions to just coreversions
// only for the purposes of this snippet
var coreversions = ["1.6.3","1.6.4","1.6.5","1.6.6","1.7.0","1.7.2"];
if (coreversions) {
var options = coreversions.map(
versions => ({value: versions, label: versions})
);
}
console.log(options);
// logs out an array of objects:
// [
// { value: '1.6.3', label: '1.6.3' },
// { value: '1.6.4', label: '1.6.4' },
// { value: '1.6.5', label: '1.6.5' },
// { value: '1.6.6', label: '1.6.6' },
// { value: '1.7.0', label: '1.7.0' },
// { value: '1.7.2', label: '1.7.2' }
// ]
I think your map function is returning an array of strings instead of objects. Should be like:
return { value: '${versions}', label: '${versions}' }
Note how the above does not have the ticks surrounding the entire line.
React-Select expects an array of objects, not an array of strings.
You can loop through the data, put these values in a object and push it in an array like the following:
var results = ["1.6.3", "1.6.4", "1.6.5", "1.6.6", "1.7.0", "1.7.2"];
var selectData= [];
for (result of results) {
selectData.push({
value: result,
label: result
});
}
console.log(selectData);
This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Closed 9 months ago.
I'm running an express.js app that has a few apis feeding data to dropdown boxes. The data returned is in the form:
[
{
key: 'blah',
value: 'Blah Blah'
},
{
key: 'foo',
value: 'Foos'
},
{
key: 'bar',
value: 'Bars'
},
{
key: 'baz',
value: 'Bazingo'
}
];
where key is my option key and value is the display text. The structure of this array is fixed and I know for a fact that I'll always have key and value as the fields in each object in the array.
When I try to validate the form submitted (additional server side validation), I'd like to cross-reference the value provided for a field against all the values for "key" in the array (blah, foo, bar, baz). Given that this is going to be a frequently used route, I'd like to avoid iterating over the array to find the permitted values, every single time. Is there a simpler way to do this? In other words, I know I can use:
permittedValues = [];
for (i = 0; i < array.length; i++){
permittedValues[i] = array[i]["key"];
}
but I'd like to avoid this for loop, if possible.
P.S: This seems to be a fundamental question and the answers I found online didn't exactly answer my question. So, apologies if this has already been asked and answered.
You could map:
permittedValues = array.map(function(value) {
return value.key;
});
In ES6/ES2015 it's even prettier with arrow functions:
permittedValues = array.map(value => value.key);
It might be prettier, but it's probably not faster than a for() loop.
Using lodash,
Since lodash 4.x the _.pluck function has been removed in support to map function.
so you can achieve the desired task by:
import _ from 'lodash'
_.map(items, 'key');
Ref: What happened to Lodash _.pluck?
Pure Javascript ES6
array.map(value => value.key);
Underscore/Lodash
_.map(value,'key')
If you are using ES6 javascript version you can do something like the one below:
const arrayData = [
{
key: 'blah',
value: 'Blah Blah'
},
{
key: 'foo',
value: 'Foos'
},
{
key: 'bar',
value: 'Bars'
},
{
key: 'baz',
value: 'Bazingo'
}
];
const foodBar = arrayData.find(item => item.key === "baz");
const resultValue = foodBar['value']; // here the extracted value is by key
In the current versions of Javascript you need a loop do to it.
However you can use a module like npm `lodash' to make it look simpler
var _ = require('lodash')
var permittedValues = _.pluck(array, 'key')
link to pluck documentation
You could extract the values via map, and form them into a regex to match values against.
Example: http://repl.it/X0V
var items=
[
{
key: 'blah',
value: 'Blah Blah'
},
{
key: 'foo',
value: 'Foos'
},
{
key: 'bar',
value: 'Bars'
},
{
key: 'baz',
value: 'Bazingo'
}
];
var toReg = items.map(function(obj){
return obj.key;
}).join('|');
var regex = new RegExp('^('+ toReg +')$');
//To test the regex
var itemsToTest = ['blah', 'Pies', 'foo', 'Bazingo'];
itemsToTest.forEach(function(key){
if(regex.test(key)){
console.log(key);
}
});
Try this..
const myArray = [
{
key: 'blah',
value: 'Blah Blah'
},
{
key: 'foo',
value: 'Foos'
},
{
key: 'bar',
value: 'Bars'
},
{
key: 'baz',
value: 'Bazingo'
}
];
const resObject = myArray.find(item => item.key === "foo");
// Here you can access object which you want
console.log(resObject);
Also you can refer this answer..
Find object by id in an array of JavaScript objects