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"}
You can make an object instead of array like this
const arrayValue={};
arrayValue['1'] = value1;
// Same for the other values
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"
}
var obj = {}
for (var i in arrayValue){
obj[i] = arrayValue[i];
}
console.log(obj)
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.