i have array data in the format given below
const data= [
{
name: "productname",
id: "1356",
price: "0.00",
category: "Health",
position: "1",
list: "New Products",
stocklevel: "20",
brand: "Health"
},
{
name: "productname2",
id: "5263",
price: "0",
category: "Hair",
position: "2",
list: "New Products",
stocklevel: "",
brand: "Hair"
}]
from this data i want only product name of each product by difference of product1 , product2. for example i want the data in format of string by comma separated values like given below:-
product1name: "productname",
product2name: "productname2",
...
i tried using map function but not able to take only one or two values from whole array data. here is the code what i tried
var dataByComa = '';
var Values = data
.map(function (p, i) {
return Object.keys(data[i]).map(function (k) {
return "prod" " " ": " JSON.stringify(data[i][k]);
});
}).map(function (v) {
return v.join(",\n"); });
var commaValues = Values.join(",\n");
return commaValues;
with this code i can able to convert array data into comma separated values but i want only productnames.
Note :- Without using template template literals.
CodePudding user response:
Edit: I'm more clear on what the OP was looking for now - here is an answer that fulfills all the requirements
let commaValues = ""
for (let i = 0; i < data.length; i ) {
commaValues = ("product" (i 1) "name: " "\"" data[i]["name"] "\", ")
}
// result: 'product1name: "productname", product2name: "productname2", '
CodePudding user response:
You can do that using reduce. It takes a function as first and an initial value as second parameter (here an empty object {}). The variable "previous" keeps track of the current state of the (initially empty) new object while the function adds the name of every single Element from the "data" array to the object.
var result = data.reduce((previous, element) => {
previous[element.name] = element.name;
return previous;
}, {})
EDIT: As i realized, you actually want a string as result. In that case you could do:
var result = data.reduce((previous, element) => {
previous[element.name] = element.name;
return previous;
}, {})
var csvWithBrackets = JSON.stringify(result)
var csv = csvWithBrackets.substring(1, csvWithBrackets.length-1)
However the answer from Pzutils seems more compact.
CodePudding user response:
You can iterate through the data and assign the value to an external variable like this:
let finalData = {}
data.forEach((item, index) => {
finalData[`product${index 1}name`] = item.name
})