---
title: "setPath"
description: "在对象指定路径写入新值，支持深层嵌套路径和自动创建中间对象，返回新对象。"
seo_title: "setPath"
seo_description: "Set a value at a dot or bracket path inside an object, creating intermediate objects as needed and returning the updated object."
canonical_url: "https://core.mhaibaraai.cn/docs/helpers/path/set-path"
---
# setPath

> 在对象指定路径写入新值，支持深层嵌套路径和自动创建中间对象，返回新对象。

## 用法

`setPath` 函数用于在对象指定路径写入值。

```ts
import { setPath } from '@movk/core'

const obj: any = {}
setPath(obj, 'a.b[0].c', 7)
// obj => { a: { b: [{ c: 7 }] } }

setPath(obj, 'a.b[2].d', 8)
// 数组自动扩容到长度 3
// obj.a.b[2] => { d: 8 }

setPath(obj, 'a.0.b', 1) // 点语法数字键保持为字符串键
// obj => { a: { 0: { b: 1 } } }
setPath(obj, 'a[0].b', 2) // 索引用方括号
// obj.a[0].b => 2
```

## API

### `setPath(object, path, value)`

在对象指定路径写入值。

### 参数

**object** (`T`) *required*: 目标对象(原地修改并返回同一引用)。

**path** (`PathInput`) *required*: 路径字符串或片段数组。

**value** (`unknown`) *required*: 要写入的值。

### 返回值

**返回值** (`T`): 原对象(已修改)。

## Changelog

See commit history for [src/helpers/path/setPath.ts](https://github.com/mhaibaraai/movk-core/commits/main/src/helpers/path/setPath.ts).


## Sitemap

See the full [sitemap](/sitemap.md) for all pages.
