Convert array of object to once string with only values - javascript

I have an array of object as below
const result = [
{ email: 'me#example.com' },
{ email: 'c#examples.com' }
];
Expected Output :
"me#example.com, c#examples.com"
How can i get the desired output?

result.map(({email}) => email).join(', ')
iterate thru the array and join it.

Related

Convert array [ {''} ] to list [ ''] [duplicate]

This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Closed last month.
I would like to convert array to a list like :
This :
[ RowDataPacket { id_name: '' } ]
To :
[ '' ]
I just want a list, whitout name, no 'id_name'
Create a new empty array and when looping your rowDataPacket array, push them to new array.
Example;
// your array = rowDataPackets =[{id_name:''},{id_name:''},...]
const CleanArray = [];
rowDataPackets.forEach( ({ id_name : idName }) => { CleanArray.push(idName) });
console.log(CleanArray);
// CleanArray = ['','',...]
You can use Map Array method to iterate over this arr and get the key
const result = [ RowDataPacket { id_name: '' } ].map( item => item.id_name )

JavaScript: format CSV array to Json format

I have the following array which I have extracted from csv file
array
[
{ "Date;Department;Value": "2022-09-08;dept1;7856"},
{ "Date;Department;Value": "2022-09-08;dept2;9876"}
]
I need the following output:
[
{
"Date":"2022-09-08",
"Department":"dept1",
"Value":7856
},
{
"Date":"2022-09-08",
"Department":"dept2",
"Value":9876
}
]
That's quite doable, just take the problem step by step:
const array = [
{ "Date;Department;Value": "2022-09-08;dept1;7856" },
{ "Date;Department;Value": "2022-09-08;dept2;9876" }
];
const result = array
.map(Object.entries) // Convert the objects to more easily accessible arrays.
.map(([[k, v]]) => { // Grab the key / value strings
const keys = k.split(';'); // Split the keys into separate entries.
const values = v.split(';'); // Split the values into separate entries.
// Join the array of keys with the array of values, parsing numbers if possible.
return keys.reduce((obj, key, i) => {
obj[key] = isNaN(values[i]) ? values[i] : Number(values[i]);
return obj;
}, {});
});
console.log(result);

Find empty keys in array of object using javascript (Es6,typescript)

I have an array of objects. In that array of objects I have to find which keys have empty value with index of array. Array list is given below:
let fruits=[
{name:"apple",quantity:2,price:"" },
{name:"orange",quantity:" ",price:"2"},
{name:"banana",quantity:" ",price:""}
];
so here i have to find any of object key having empty value which should return key with index. i have tried using .findIndex() and other methods but unfortunately i can't. I am new to es6 and typescript. i need to check key with empty value in array of object.
This should do what you want. It will "map" through your array and will find for each object the keys of properties that are empty or a blank string. Then the so filtered items are "mapped" again with all the found keys being "joined" into a comma separated list (property "f") together with the "id" of the object. As a last step I filter out all those objects where the "f" property actually contains key name(s).
let fruits=[
{name:"apple",quantity:2,price:"" },
{name:"orange",quantity:" ",price:"2"},
{name:"pineapple",quantity:3,price:5},
{name:"banana",quantity:" ",price:""}
];
let empty=fruits.map(f=>
Object.keys(f).filter(k=>!(""+f[k]).trim()))
.map((f,i)=>({id:i,f:f.join(',')}))
.filter(f=>f.f)
console.log(empty)
In my example I added another fruit ("pineapple") with a complete set of filled properties. My snippet considers strings containing only blanks as "empty".
Please try the following example
let fruits = [
{ name: "apple", quantity: 2, price: "" },
{ name: "orange", quantity: "", price: "2" },
{ name: "banana", quantity: "", price: "" },
];
const output = fruits.reduce((previousValue, currentValue, currentIndex) => {
const keys = Object.keys(currentValue).filter((key) => !currentValue[key]);
if (keys.length) {
previousValue[currentIndex] = keys;
}
return previousValue;
}, {});
console.log(output);
See
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
Assuming you're looking to get fruits that do not have a price value, you'll need to run a filter since your fruits is an array.
let emptyPriceFruits = fruits.filter((fruit) => !fruit.price)
Additional reading on .filter - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
How about this one, by taking entries of object and then using filter to identify deuplicate values:
var fruits=[ {name:"apple",quantity:2,price:"", pal:null }, {name:"orange",quantity:" ",price:"2"}, {name:"banana",quantity:" ",price:""}];
var emptyResult = fruits.map(k=>Object.fromEntries(Object.entries(k).filter(([k,v])=>typeof v=='string' && !v.trim())));
console.log(emptyResult);

Unable to filter the non empty array data using lodash filter

An array is as follows :
const arr = [ { name: 'Aditya', hobbies: ['Football', 'Basketball'] },
{ name: 'Amitabh', hobbies: [] },
{ name: 'Akhsara', hobbies: ['Basketball'] },
{ name: 'Aia', hobbies: [] }
];
Using filter function as follows:
public getDatas(hobby) {
const data = _.filter(arr, {hobbies : hobby === 'Unclear' : [] ? [hobby]} );
}
I have some how set the Unclear hobbies to empty arrays, when it is Unclear then it is NOT returning me the data with hobbies : [] instead it is returning me the whole of arr.
The predicate (second argument) of _.filter indicates the property or properties to filter. Since hobbies is a string array, there is no hobby property of hobbies.
You can use Array.prototype.includes like this:
const data = _.filter(arr, item => item.hobbies.includes('Unclear'));
// If you want to extract just the 'hobbies' object, not the parent
const hobbies = _.map(data, 'hobbies');

Could not map two array using JavaScript/Node.js

I could not map two array of json data as per key value using JavaScript. My code is below:
var userdata=[{'email':'a#gmail.com','name':'Rajj'},{'email':'b#gmail.com','name':'Rajesh'}];
var userdata1=[{'email':'a#gmail.com','address':'rasukgarh'}];
var finalArr=[];
userdata.map(item => {
userdata1.map(item1 => {
if(item.email==item1.email){
finalArr.push(Object.assign(item, item1));
}else{
finalArr.push(Object.assign(item, item1));
}
})
})
console.log('all Data',finalArr);
}
Here my requirement is if same email id is present in both array then the additional data of second array will merge with first one. If 1st array has some data and based on the email value no data is present inside second array then in hat case only first array data will push to resultant array. Here my expected output is.
finalArr=[{'email':'a#gmail.com','name':'Rajj','address':'rasukgarh'},{'email':'b#gmail.com','name':'Rajesh'}]
But in my case I could not get like this.
You can use map() to create new array and find() to find objects with same email in second array and Object.assign() to create copy of object and assign objects from second array.
var userdata=[{'email':'a#gmail.com','name':'Rajj'},{'email':'b#gmail.com','name':'Rajesh'}];
var userdata1=[{'email':'a#gmail.com','address':'rasukgarh'}]
var result = userdata.map(function(e) {
var find = userdata1.find(a => a.email == e.email);
return Object.assign({}, e, find)
})
console.log(result)
var userdata = [{ 'email': 'a#gmail.com', 'name': 'Rajj' }, { 'email': 'b#gmail.com', 'name': 'Rajesh' }];
var userdata1 = [{ 'email': 'a#gmail.com', 'address': 'rasukgarh' }];
userdata.map(function(item) {
userdata1.map(function(item1) {
if (item.email == item1.email) {
// modify the original userdata array item
Object.assign(item, item1);
}
})
})
console.log(userdata);

Categories