I want to add new element to array which inside nested object by using its path. I searched but didn't anything about that. For example my object is :
const sample = {
enum: 4,
key: "COMMON_TYPE",
steps: [
{
title: "STEP ONE",
description: "des1",
instructions: [
{
icon: "step_power",
label: {
text: "METHOD_OVEN_DEFAULT_STEP_ONE_ICONTEXT",
color: "A11111",
location: "top",
},
},
],
},
{
title: "STEP TWO",
description: "des2",
instructions: [
{
icon: "step_power",
label: {
text: "METHOD_OVEN_DEFAULT_STEP_TWO_ICONTEXT_ONE",
color: "A11111",
location: "top",
},
},
],
},
],
};
and I want to new element for this path 'steps.0.instructions' and second item should be copy of first index for that array. In onClick event I got path of key as 'steps.0.instructions'. Now I need a function which return newObject for given issue. My output should be like this:
const sample = {
enum: 4,
key: "COMMON_TYPE",
steps: [
{
title: "STEP ONE",
description: "des1",
instructions: [
{
icon: "step_power",
label: {
text: "METHOD_OVEN_DEFAULT_STEP_ONE_ICONTEXT",
color: "A11111",
location: "top",
},
{
icon: "step_power",
label: {
text: "METHOD_OVEN_DEFAULT_STEP_ONE_ICONTEXT",
color: "A11111",
location: "top",
}
},
],
},
{
title: "STEP TWO",
description: "des2",
instructions: [
{
icon: "step_power",
label: {
text: "METHOD_OVEN_DEFAULT_STEP_TWO_ICONTEXT_ONE",
color: "A11111",
location: "top",
},
},
],
},
],
};
Thanks..
CodePudding user response:
use unshift function to add new item to the beginning of array. like
sample.steps.instructions.unshift( {
icon: "step_power#2",
label: {
text: "METHOD_OVEN_DEFAULT_STEP_ONE_ICONTEXT",
color: "A11111",
location: "top",
}
})
CodePudding user response:
If you wanna copy an object, lookup what deep copy means.
Here are some helpful links:
CodePudding user response:
This does what you ask for.
I used JSON.parse(JSON.stringify(sample))
for a deep copy. You can do it in your preferred way.
const addToPath = (sample, path) => {
const parts = path.split(".")
const newSample = JSON.parse(JSON.stringify(sample))
const instructionsArray = newSample[parts[0]][parts[1]][parts[2]]
instructionsArray.push(instructionsArray[0])
return newSample
}
And it will be called as follows:
const newSample = addToPath(sample, "steps.0.instructions")