Home > Blockchain >  How to convert Array of string to List of string in react js
How to convert Array of string to List of string in react js

Time:01-07

How to add a string item to the list in react js. sample Code:

const value1="Book";
const value2="Pen";
const value3="Note";

const arrayValue=[];
arrayValue.push(value1);
arrayValue.push(value2);
arrayValue.push(value3);
console.log(arrayValue);

Output is : ["Book","Pen","Note"];
expected output is : object:{[0]."Book",[1]."Pen",[2]."Note"}

CodePudding user response:

You can make an object instead of array like this

const arrayValue={};
arrayValue['1'] = value1;
// Same for the other values

CodePudding user response:

var obj = {}
for (var i in arrayValue){
    obj[i] = arrayValue[i];
}

console.log(obj)

CodePudding user response:

const value1="Book";
const value2="Pen";
const value3="Note";

const arrayValue=[];
arrayValue.push(value1);
arrayValue.push(value2);
arrayValue.push(value3);
console.log(arrayValue);
const newObj = {}
for (let i = 0; i < arrayValue.length; i  ) {
  newObj[i] = arrayValue[i]
}
console.log(newObj)

This is what is logged

["Book", "Pen", "Note"]
[object Object] {
  0: "Book",
  1: "Pen",
  2: "Note"
}
const value2="Pen";
const value3="Note";

const arrayValue=[];
arrayValue.push(value1);
arrayValue.push(value2);
arrayValue.push(value3);
console.log(arrayValue);
const newObj = {}
for (let i = 0; i < arrayValue.length; i  ) {
  let string = `[${i.toString()}]`
  newObj[string] = arrayValue[i]
}
console.log(newObj)

This is Logged

["Book", "Pen", "Note"]
[object Object] {
  [0]: "Book",
  [1]: "Pen",
  [2]: "Note"
}

CodePudding user response:

Your "expected output" is an object. This has nothing to do with react though...

Try this:

list = ["1", "2", "3"];
object = {};

for(x=0; x < list.length; x  ){
  object[x] = list[x];
}
console.log(object)

  •  Tags:  
  • Related